0

I want to do a ton of animation with images on canvas; is it more beneficial to use a canvas element as a buffer for the image (so that we do not have to resize again) or is it more beneficial to use an img element as a buffer?

Or is there actually a better way, a must-do if performance is top-priority that I should do and I'm missing?

Also, why is "clearing" the canvas such a slow operation? My background is xna programming for windows phone 7 and "clearing" the whole screen is one of the fastest operation.

Also, should I "clear" the canvas by setting width=width or should I do a drawRect(0,0,width,height) ?

rgettman
  • 176,041
  • 30
  • 275
  • 357
Pacerier
  • 86,231
  • 106
  • 366
  • 634
  • for height and width see http://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5 – Brij May 30 '11 at 10:31

1 Answers1

1

You should use canvas elements as buffers for transformed images and align your drawImage calls on integer coords. Software canvas implementations get slow once you need to transform the image (because transforming = resampling = slow.)

See: http://jsperf.com/canvas-drawimage

Clearing the canvas, use clearRect: http://jsperf.com/canvas-clear-speed

Ilmari Heikkinen
  • 2,711
  • 1
  • 19
  • 14
  • wait do you mean that it is faster to do `drawImage(c)` compared to `drawImage(img)` ? (because the tests prove otherwise..?) – Pacerier Jun 01 '11 at 19:01
  • I mean that if you have a transformed image (like, rotated or scaled or something) that you're drawing a lot, you should cache the transformed version into a canvas for best perf. – Ilmari Heikkinen Jun 02 '11 at 09:41
  • ok cool, but for normal images that i load from a url.. should i load it into a canvas and `DrawImage(c)` or should i simply `drawImage(img)` ? – Pacerier Jun 03 '11 at 02:59
  • simply drawImage(img) these days I guess. Chrome used to have a prob with drawImage(img) using a way more expensive resampling algo than drawImage(canvas), but I think it's fixed now. YMMV of course. – Ilmari Heikkinen Jun 03 '11 at 14:47
  • @IImari Heikkinen . ok so what you are trying to say is when there's doubt go for `drawImage(canvas)` because absolutely 100% even if its not faster, it will `never` be slower. Right? – Pacerier Jun 03 '11 at 14:52
  • Yes. (With the following caveats: the first draw takes longer because you need to copy the image to the canvas and the cache canvases use more memory. And I can't know what is going to happen to the implementations in the future. But today, canvases are faster.) – Ilmari Heikkinen Jun 03 '11 at 15:42