HTML and CSS Reference
In-Depth Information
var body = "ctx.beginPath();";
for(var i = 0; i < svg.length; i+=3) {
var pos = svg[i + 1] + "," + svg[i + 2];
if(svg[i] == "M") { body += "ctx.moveTo(" + pos + ");"; }
if(svg[i] == "L") { body += "ctx.lineTo(" + pos + ");"; }
var func = new Function("ctx", body + "ctx.fill();");
Listing 16-14. The Generated Codes
After generating drawing codes as a function, just use this function. No more parsing is needed. To adjust
position or scaling, you just use an affine transformation.
Use GPU Effectively
In the old days, browsers drew Canvas with software rendering using the CPU, not GPU. But almost all current modern
browsers support GPU rendering, increasing the importance of techniques that utilize the GPU.
When you need to draw with the GPU, you have to transfer the image data from CPU to GPU. You don't need to
transfer every time because your browser tries to cache the image data inside the GPU. You need to transfer image
data if you want to draw an image not existing in the GPU cache.
Optimizations for using the GPU are very effective when you use drawImage a lot. drawImage is very fast as is,
with significant advantages when internally utilizing the GPU cache. It is a very good idea to design to use the GPU
cache effectively.
However, there is no obvious way to use the cache precisely; it depends on the implementation of browsers.
So you need to struggle to put the image in the cache area preferably. The basic strategy is to use a small number of
images. Sometimes it is also effective to avoid large images because the browser may need to clear and overwrite the
existing GPU cache area.
In addition, please keep in mind that browsers never use the cache when you indicate Canvas at the first
argument of drawImage. If you want to use the GPU cache with canvas such as in-memory canvas, you can convert
the Canvas element to img element. See Listing 16-15.
Listing 16-15. Convert from Canvas to Img
var src = canvas.toDataURL();
var img = document.createElement("img");
img.src = src;
It needs initial costs to convert from canvas to img, but after that you can push the image to the GPU cache.
This is an especially effective technique for game engines.
Search WWH ::

Custom Search