Canvas Background

Yesterday I drew a grid on a canvas that I will now send to the background. This allows me to do an animation or whatever I want without redrawing the background each time. Its actually very simple to do.

// once you've fully composed your background, grab it as a PNG (saves transparency)
var png = canvas.toDataURL("image/png");
// set the element's background to the base64 PNG = "url("+png+")";

Note: toDataURL() does not require you specify the image mime type; the default is “image/png”.

After setting the background you can inspect the element in Chrome and see that the HTML source now contains the base64 data URL.

<canvas id="c" style="background-image: url(data:image/png;base64,iVBORw0KGgo.........AABJRU5ErkJggg==); "></canvas>
<!-- I cut out some data for brevity -->

Another example I have seen is drawing a chart, sending it to the background and then drawing the chart data. If the chart data changes you don’t have to redraw the chart itself just the data points/lines/bars. You effectively get two layers.

Another cool idea would be use the base64 PNG data as the URL for other elements backgrounds or even the image source.  There are advantages and disadvantages and you can read more here.


No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *