Fastest algorithm to draw a crossword grid in <canvas>?

Viewed 4128

I'm rendering a grid of cells, very much like the grid you find in a crossword puzzle, but using four different colors to fill each cell (not only black or white).

The grid size is about 160x120, and I need to render it as fast as possible, as it will be used to display a Cellular automaton animation.

I have tried two different approaches to render the grid:

  • Render each cell using something like:

    var w = x + step;
    var h = y + step;
    canvasContext.fillStyle=cell.color;
    canvasContext.fillRect(x+1,y+1,w-1,h-1);
    canvasContext.strokeRect(x,y,w,h);
    
  • Render the all of cells without the border, and then render the grid lines using:

    var XSteps = Math.floor(width/step);
    canvasContext.fillStyle = gridColor;
    for (var i = 0, len=XSteps; i<len; i++) {
        canvasContext.fillRect(i*step, 0, 1, height);
    }
    //Similar thing for Y coord
    

Both algorithms perform poorly: it is slower to draw the grid than the cells in both cases. Am I missing something? How can I optimize those algorithms? Is there another way I should try?

Note: the grid moves, as the user can displace it or zoom the view.

The general question will be: what is the fastest algorithm to draw a grid of cells on a element?

3 Answers
Related