Skip to content
Advertisement

A fast way to draw/update colors of a 2d array of squares in JavaScript

I’m working on a game in JavaScript which has a 2d array of squares that update their background colors every frame.

So far I’ve been using a borderless DOM table for this task by setting the style.backgroundColor of each cell every frame, but it’s fairly slow. Is there a way to do this faster?

Advertisement

Answer

For this kind of computation directly drawing the squares in a single canvas should be faster (JS compiles to rather efficient native code in these days, and the small overhead that you would get is probably much less than the overhead of dealing with the DOM and .style would introduce).

Of course only testing with the devices/browsers you need to support can provide real answers (and note that things may change over time).

Example code:

let ctx = canvas.getContext("2d");
   
setInterval(function(){
    for (var y=0; y<256; y+=16) {
        for (var x=0; x<256; x+=16) {
            var r = Math.floor(Math.random()*256);
            var g = Math.floor(Math.random()*256);
            var b = Math.floor(Math.random()*256);
            ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
            ctx.fillRect(x, y, 16, 16);
        }
    }
}, 10);
<canvas id="canvas" width=256 height=256></canvas>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement