Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of background-canvas vs. regular canvas

A while back webkit (and thus Safari) began to support CSS canvas-backgrounds for elements (Source: http://www.webkit.org/blog/176/css-canvas-drawing/).

This could greatly simplify the creation of games and multimedia, in that you dont need to inject a canvas-tag into a DIV (for instance), but simply hook into the background of the DIV directly. Something like this perhaps:

<div id="gameview"
style="background: -webkit-canvas(myscreen); width: 320px; height: 480px;">
</div>

<script>
    var target = document.getElementById("gameview");
    var wd = target.clientWidth;
    var hd = target.clientHeight;
    var context =  document.getCSSCanvasContext("2d", "myscreen", wd, hd);
    /* draw stuff here */
</script>

I was wondering, are there any speed penalties involved in this? In theory i think drawing to a background canvas should be faster than drawing to a canvas tag, especially if the target element is empty.

Have anyone tested this for high-speed demos or games?

like image 206
Jon Lennart Aasenden Avatar asked Nov 24 '11 23:11

Jon Lennart Aasenden


People also ask

Can you use Canvas as background?

but u can attain a canvas element as background just by using CSS.

Which is faster SVG or Canvas?

SVG gives better performance with smaller number of objects or larger surface. Canvas gives better performance with smaller surface or larger number of objects. SVG can be modified through script and CSS. Canvas can be modified through script only.

Is SVG faster than Div?

The long answer: Those SVG DOM references mean that some of the footwork of dealing with the things you draw is done for you. And SVG is faster when rendering really large objects, but slower when rendering many objects. A game would probably be faster in Canvas. A huge map program would probably be faster in SVG.


1 Answers

According to my tests (also run in reversed order), original canvas element is slightly but consistently slower than the background canvas.

Chromium 17 draws a chess-board 10000 times in:

  • ~470 ms on the background canvas
  • ~520 ms on a canvas element

Safari 5 shows similar dynamics.

Try setting the number of iterations to 100000, results should be consistent with the above.


Update half a year later

We tried the background canvas approach in one project (as an attempt for a minor optimization), and the results were dramatically opposite to our expectations. The whole thing (two layers: one – a div with background canvas, the other – a regular canvas) became marginally slower. In fact, when we introduced the background canvas, the app became slow as hell. Tested in Chrome 21.

I definitely would not vouch for the background canvas to be faster in all situations.

like image 199
katspaugh Avatar answered Oct 12 '22 18:10

katspaugh