How can I outsource worker processes within a for loop?

63 Views Asked by At

I would like to outsource the following hungry process in a worker within the loop:

encoder.addFrame(ctx);

Unfortunately, I have not been able to do this with node.js worker threads so far. Perhaps I have lacked the right approach so far. In my attempts, I was unable to pass either the encoder or the ctx object to the worker. Maybe my plan doesn't work at all with node.js Worker threads... I don't know. Maybe someone of you has a solution or knows another way to outsource the process in the background?

Here is the complete code:

generate: function (cb) {

    const GIFEncoder = require('gif-encoder-2');
    const encoder = new GIFEncoder( Number(200), Number(200), 'neuquant', true);
    encoder.start();
    encoder.setRepeat( 0 );
    encoder.setDelay(1000);
    encoder.setQuality(10);

    const { createCanvas, registerFont } = require('canvas');
    const canvas = createCanvas( Number(200), Number(200) );
    const ctx = canvas.getContext('2d');

    for (let i = 0; i < 10; i++) {

        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(200, 0);
        ctx.lineTo(200, 200);
        ctx.lineTo(0, 200);
        ctx.closePath();
        ctx.fillStyle = 'blue';
        ctx.fill();

        ctx.fillStyle = 'white';
        ctx.font = ['72px', 'Open Sans'].join(' ');
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(i.toString(), 100, 84 + ctx.measureText(i.toString()).actualBoundingBoxAscent / 2);

        encoder.addFrame(ctx); // Process this step in a worker!

    }

    encoder.finish();

    return encoder.out.getData();

}
0

There are 0 best solutions below