HTML and CSS Reference
In-Depth Information
As you can see in Figure 8-4 , the initialization took approximately 22 ms, which is a lot of time but it's not worrying.
The rendering, however, took more than 6.5 seconds. And keep in mind that that's on every frame.
I previously mentioned that an easy optimization would be to call only the paintCell() function if the current
cell was within the viewport, so let's do that. All you need to do is to modify the code in Listing 8-14 to check that the
cell is within function, which gets you the code in Listing 8-15.
Listing 8-15. Checking that a Cell Is Within a Function
console.time("Grid Rendering");
for ( ; i < gridRows ; ++i ) {
for ( j = 0 ; j < gridCols ; ++j ) {
if (Grid[i][j] === 1) {
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");
Run this example and open the console. Note that you have made a remarkable improvement to the
performance. For my part, I sped up the rendering routine from ~6.5 seconds to a mere ~8.5 ms.! See Figure 8-5 .
 
Search WWH ::




Custom Search