HTML and CSS Reference
In-Depth Information
// Paint the "background"
var i = 0,
j = 0;
console.time("Grid Rendering");
You then declare two counters that you'll be using in two
for()
loops, as shown in Listing 8-19.
Listing 8-19.
Declaring Two Counters that to Use in the Two
for()
Loops
for ( ; i < gridRows ; ++i ) {
for ( j = 0 ; j < gridCols ; ++j ) {
if (Grid[i][j] === 1) {
// Only render the cell if it's within the viewport
if ((j * cellWidth) >= 0 && (j * cellWidth) < viewportWidth &&
(i * cellHeight) >= 0 && (i * cellHeight) < viewportHeight) {
paintCell(ctx,
j * cellWidth,
i * cellHeight,
cellWidth,
cellHeight);
// Print the current values of i and j for each cell
ctx.fillStyle = '#000';
ctx.font = '10px Arial';
ctx.textAlign = 'center';
ctx.fillText(i + ' ' + j,
j * cellWidth,
i * cellHeight);
// Set that position as painted
Grid[i][j] = 0;
}
}
}
}
console.timeEnd("Grid Rendering");
// There's no need to go through all this logic on every frame
shouldRepaint = false;
Currently, the value of
gridCols
and
gridRows
is 1000. This basically means that your
for()
loops are iterating
through every single one of the cells, checking if they are within the viewport one by one. Surely there must be a way
to make things faster. And obviously, there is.