开发者

Why does drawing an animated gif on canvas only update after reselecting the tab?

I would li开发者_Python百科ke to display an animated gif on canvas with some transformations applied. To test things, I'm currently just trying to display the animated gif on the canvas, so that it is essentially equal to displaying the gif as a regular <img> tag.

I'm using Chrome and webkitRequestAnimationFrame. On each request frame, I draw the image. When the gif frame changes, this should be reflected on the canvas. This works only partially:

  • Just watching the canvas does not make it update. Instead, one, still frame is begin drawn.
  • Reselecting the tab (i.e. selecting another and selecting the canvas tab again) does update it to a new frame, but after that it freezes again.

This is a fiddle I set up: http://jsfiddle.net/eGjak/93/.

How can I draw an animated gif on canvas with it actually animating?


Answer no longer valid

It looks like the behavior described here (writing an img tag referencing an animated gif to a canvas results in different frames of the gif being written if the img is part of the DOM or visible) has changed at least in Chrome. There may or may not be documentation of what is correct behavior for this. :)

Also, webkitRequestAnimationFrame no longer has the behavior of taking one additional argument, an element X such that when X is not visible, the requested function will not run. For performance and battery life reasons, you may want many of the functions that you pass to requestAnimationFrame to check for visibility before they do anything that will require drawing.

Before:

Check out a fixed version:

http://jsfiddle.net/eGjak/96/

If you add a console.log() to the function that paints the image, you'll see that it is being called. The problem seems to be that the image itself does not animate, probably because the browser does not bother to update an animated image that is not part of the DOM.

My solution was to make the animated gif part of the DOM and size 0 and it works just fine.

You can verify that the animation is being shown on the canvas and not in the image tag by loading up http://jsfiddle.net/eGjak/96/show/ and inspecting the elements with ctrl-shift-I on Windows or Linux / alt-cmd-I.

EDIT: Here's a bonus!

webkitRequestAnimationFrame takes one more argument than the Mozilla equivalent to allow your animation to only run when the element that is being animated is visible. Check out

http://jsfiddle.net/kmKZa/8/

and open up the console. You'll see that when you hide the canvas, the animation function stops being called. When you toggle the canvas visible again, the animation function will be called again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜