Generating Images with Serverless


programming

One thing I’ve always wanted to do was write a serverless function that could generate CS:GO crosshair images. The serverless platform that I chose is Cloudflare Workers which utilizes a vast edge network and supports 0 ms cold starts.

Writing a serverless function for this task didn’t seem too difficult, but I quickly ran into some issues.

Using node-canvas

Modern browsers are equipped with the Canvas API which makes it extremely easy to create 2D graphics. Although this API is meant to be used in the browser, Automattic (the maker of WordPress) has an implementation of Canvas for Node.js called node-canvas.

However, using node-canvas has a number of problems.

Workers limits scripts to 1 MB. Node-canvas uses Cairo as a native dependency. Suppose it was possible to compile Cairo into a WASM module it would very likely exceed 1 MB.

There is another library called node-pureimage which is a pure JS implementation of the Canvas API.

Free Workers limits the CPU runtime of functions to 10 ms for their free plan. Having the function run under the 10 ms CPU runtime limit proved to be difficult due to the complexity of generating images on the fly. Node-pureimage uses a library called pngjs which in itself, is very useful in generating PNGs through a low-level interface.

Using pngjs

Pngjs provides an incredibly simple interface for manipulating individual pixels.

The data to the PNG image is represented as an array with each pixel represented as a group of 4 values (red, green, blue, alpha (opacity)).

For example, if you want to color any given pixel, you could do the following:

const idx = (png.width * y + x) << 2; // same as (png.width * y + x) * 4
png.data[idx] = red;
png.data[idx + 1] = green;
png.data[idx + 2] = blue;
png.data[idx + 3] = alpha;

Using pngjs was enough to keep the function from timing out and made generating crosshair images surprisingly quick!

By passing the crosshair command settings as query parameters, we have all the information we need to draw a crosshair.

https://crosshair.darenliang.com/?cl_crosshaircolor=0&cl_crosshairsize=2.5&cl_crosshairgap=-3

Here are some example crosshairs from the best CS:GO players as of writing, served from the serverless function.

s1mple&rsquo;s crosshair image

s1mple's crosshair

ZywOo&rsquo;s crosshair image

ZywOo's crosshair

NiKo&rsquo;s crosshair image

NiKo's crosshair

What I’ve Learned

Generating images with serverless functions might’ve been a bad idea, especially on a free plan! However, the experience of working around the imposed limits was actually pretty fun.

Workers does offer a paid Unbound Usage Model which allows for functions to run up to 30 seconds which is an ample amount of time. All in all, Cloudflare Workers is a great platform to get started with serverless; it has a low-latency key-value database, has more favorable pricing compared to the big three cloud providers (AWS, GCP, and Azure) and can run JavaScript code with minimal delay in large part due in running code inside isolates rather than individual containers.

Here is an interactive demo of you want to try it out for yourself: CS:GO Crosshair Preview

Source code for anyone who is curious
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
 * Import pngjs library
 * https://github.com/lukeapage/pngjs
 */
const PNG = require("pngjs").PNG;

/**
 * Headers used
 */
const headers = {
    "Content-Type": "image/png",
    "Content-Disposition": "inline; filename=\"crosshair.png\"",
    "Cache-Control": "s-maxage=31536000",
    // Used to protect your function from abuse
    // If you want anyone to use it use "*" instead
    "Access-Control-Allow-Origin": "https://www.darenliang.com"
};

/**
 * Dimensions
 */
const [width, height] = [64, 64];
const [centerX, centerY] = [Math.floor(width / 2), Math.floor(height / 2)];

/**
 * Parse str to number
 *
 * @param {string} str: string value
 * @param {number} low: lowest value
 * @param {number} high: highest value
 * @param {number} def: default value
 * @param {number} round: round reciprocal (1 / round precision)
 * @return {number} number value
 */
function parseNum(str, low, high, def, round) {
    let val = parseFloat(str);
    val = isNaN(val) ? def : val;
    if (val < low || high < val) {
        return def;
    }
    return Math.round(val * round) / round;
}

/**
 * Parse str to bool (0 - 1)
 *
 * @param {string} str: string value
 * @param {number} def: default value
 * @return {number} bool value
 */
function parseBool(str, def) {
    const val = parseInt(str) || def;
    if (val < 0 || 1 < val) {
        return def;
    }
    return val;
}

/**
 * Draw rectangle
 *
 * @param {Array<Array<Array<number>>>} pixels: pixels data
 * @param {Array<Array<number>>} coords: [[x0, y0], [x1, y1]]
 * @param {Array<number>} color: [r, g, b, a]
 */
function drawRectangle(pixels, coords, color) {
    for (let y = coords[0][1]; y < coords[1][1]; y++) {
        for (let x = coords[0][0]; x < coords[1][0]; x++) {
            pixels[y][x][0] = color[0]; // red
            pixels[y][x][1] = color[1]; // green
            pixels[y][x][2] = color[2]; // blue
            pixels[y][x][3] = color[3]; // alpha
        }
    }
}

/**
 * Draw outline
 *
 * @param {Array<Array<Array<number>>>} pixels: pixels data
 * @param {Array<Array<number>>} coords: [[x0, y0], [x1, y1]]
 * @param {number} pad: pad size
 */
function drawOutline(pixels, coords, pad) {
    const newCoords = [
        [
            coords[0][0] - pad,
            coords[0][1] - pad
        ],
        [
            coords[1][0] + pad,
            coords[1][1] + pad
        ]
    ];

    drawRectangle(pixels, newCoords, [0, 0, 0, 255]);
}

/**
 * Handle request
 *
 * @param event: event to handle
 * @return {Promise<Response>} response
 */
async function handleRequest(event) {
    const url = new URL(event.request.url);
    const key = new Request(url.toString(), event.request);
    const cache = caches.default;

    /**
     * If response is cached, return cached response
     */
    let response = await cache.match(key);
    if (response) {
        return response;
    }

    const {searchParams} = url;

    /**
     * Basic
     */
    const cl_crosshairthickness = parseNum(searchParams.get("cl_crosshairthickness"), 0.5, 5, 0.5, 2);
    const cl_crosshairgap = parseNum(searchParams.get("cl_crosshairgap"), -2, 5, 0, 1);
    const cl_crosshairsize = parseNum(searchParams.get("cl_crosshairsize"), 1, 10, 5, 1);

    /**
     * Outlines
     */
    const cl_crosshair_drawoutline = parseBool(searchParams.get("cl_crosshair_drawoutline"), 0);
    const cl_crosshair_outlinethickness = parseNum(searchParams.get("cl_crosshair_outlinethickness"), 1, 3, 1, 1);

    /**
     * Dot
     */
    const cl_crosshairdot = parseBool(searchParams.get("cl_crosshairdot"), 0);

    /**
     * Color
     */
    const cl_crosshaircolor = parseNum(searchParams.get("cl_crosshaircolor"), 0, 5, 1, 1);
    const cl_crosshaircolor_r = parseNum(searchParams.get("cl_crosshaircolor_r"), 0, 255, 50, 1);
    const cl_crosshaircolor_g = parseNum(searchParams.get("cl_crosshaircolor_g"), 0, 255, 250, 1);
    const cl_crosshaircolor_b = parseNum(searchParams.get("cl_crosshaircolor_b"), 0, 255, 50, 1);

    /**
     * Alpha
     */
    const cl_crosshairusealpha = parseBool(searchParams.get("cl_crosshairusealpha"), 1);
    const cl_crosshairalpha = parseNum(searchParams.get("cl_crosshairalpha"), 0, 255, 200, 1);
    const crosshairalpha = cl_crosshairusealpha === 1 ? cl_crosshairalpha : 255;

    /**
     * Create crosshair color
     */
    let crosshaircolor;
    switch (cl_crosshaircolor) {
        /**
         * Red
         */
        case 0:
            crosshaircolor = [255, 0, 0, crosshairalpha];
            break;
        /**
         * Green
         */
        case 1:
            crosshaircolor = [0, 255, 0, crosshairalpha];
            break;
        /**
         * Yellow
         */
        case 2:
            crosshaircolor = [255, 255, 0, crosshairalpha];
            break;
        /**
         * Blue
         */
        case 3:
            crosshaircolor = [0, 0, 255, crosshairalpha];
            break;
        /**
         * Light Blue
         */
        case 4:
            crosshaircolor = [0, 255, 255, crosshairalpha];
            break;
        /**
         * Custom
         */
        case 5:
            crosshaircolor = [cl_crosshaircolor_r, cl_crosshaircolor_g, cl_crosshaircolor_b, crosshairalpha];
            break;
    }

    /**
     * T-shaped
     */
    const cl_crosshair_t = parseBool(searchParams.get("cl_crosshair_t"), 0);


    const dot = [[centerX, centerY], [centerX, centerY]];
    /**
     * Thickness dot
     */
    {
        const thickness = cl_crosshairthickness * 2;
        const rb = Math.floor(thickness / 2);
        const lt = thickness - rb;

        dot[0][0] -= lt;
        dot[0][1] -= lt;
        dot[1][0] += rb;
        dot[1][1] += rb;
    }

    /**
     * Prefill pixels
     */
    const pixels = [];
    for (let i = 0; i < height; i++) {
        pixels[i] = [];
        for (let j = 0; j < width; j++) {
            pixels[i][j] = [];
            for (let k = 0; k < 4; k++) {
                pixels[i][j][k] = 0;
            }
        }
    }

    /**
     * Crosshair coordinates
     */
    const topBase = dot[0][1] - 4 - cl_crosshairgap;
    const bottomBase = dot[1][1] + 4 + cl_crosshairgap;
    const leftBase = dot[0][0] - 4 - cl_crosshairgap;
    const rightBase = dot[1][0] + 4 + cl_crosshairgap;
    const crosshair = [
        [[dot[0][0], topBase - cl_crosshairsize * 2], [dot[1][0], topBase]],       // top
        [[dot[0][0], bottomBase], [dot[1][0], bottomBase + cl_crosshairsize * 2]], // bottom
        [[leftBase - cl_crosshairsize * 2, dot[0][1]], [leftBase, dot[1][1]]],     // left
        [[rightBase, dot[0][1]], [rightBase + cl_crosshairsize * 2, dot[1][1]]],   // right
    ];

    /**
     * Color dot
     */
    if (cl_crosshairdot === 1) {
        /**
         * Dot outline
         */
        if (cl_crosshair_drawoutline === 1) {
            drawOutline(pixels, dot, cl_crosshair_outlinethickness);
        }

        drawRectangle(pixels, dot, crosshaircolor);
    }

    /**
     * Color crosshair
     */
    for (const [i, el] of crosshair.entries()) {
        /**
         * Check for T crosshair
         */
        if (cl_crosshair_t === 1 && i === 0) {
            continue;
        }

        /**
         * Crosshair outline
         */
        if (cl_crosshair_drawoutline === 1) {
            drawOutline(pixels, el, cl_crosshair_outlinethickness);
        }

        /**
         * Crosshair part
         */
        drawRectangle(pixels, el, crosshaircolor);
    }


    /**
     * Init PNG
     */
    const png = new PNG({
        width: width,
        height: height,
        bitDepth: 8,
        colorType: 6,
        inputColorType: 6,
        inputHasAlpha: true,
    });

    /**
     * Raster crosshair
     */
    for (let y = 0; y < png.height; y++) {
        for (let x = 0; x < png.width; x++) {
            const idx = (png.width * y + x) << 2;
            png.data[idx] = pixels[y][x][0];
            png.data[idx + 1] = pixels[y][x][1];
            png.data[idx + 2] = pixels[y][x][2];
            png.data[idx + 3] = pixels[y][x][3];
        }
    }

    /**
     * Write out buffer and cache response
     */
    const buffer = PNG.sync.write(png);
    response = new Response(buffer, {headers});
    event.waitUntil(cache.put(key, response.clone()));
    return response;
}

addEventListener("fetch", event => {
    switch (event.request.method) {
        case "GET":
            return event.respondWith(handleRequest(event));
    }
});

Comments

You can avoid authenticating giscus by commenting directly on the discussion page.