Flickering during resizing of HTML5 canvas

守給你的承諾、 提交于 2019-12-06 06:58:17

When you set canvas.width or canvas.height it clears the canvas, combined with the redrawing this causes the flicker you see.

You can mitigate this to a reasonable extent by saving the canvas to a temporary canvas before resizing and then drawing it back again afterwards.

Here's my resize function:

    function resize(width, height) {
        //Create temp canvas and context
        var tempContext = Utils.Canvas.Create2DContext(context.canvas.width, context.canvas.height);

        //Draw current canvas to temp canvas
        tempContext.drawImage(context.canvas, 0, 0);

        //Resize current canvas
        context.canvas.height = height;
        context.canvas.width = width;

        //Draw temp canvas back to the current canvas
        context.drawImage(tempContext.canvas, 0, 0);
    }

If you resize to a smaller size then the temp canvas is "overdrawn" so it'll completely fill the current canvas. However if you resize to a larger size then your temp canvas will only fill part of the current canvas. The part it doesn't fill will still flicker as it's redrawn.

If you wanted to get a bit more fancy you could try drawing a temp canvas of the correct (final) size rather than simply copying the current canvas. This would be slower but could well eliminate all flicker.

In my case I'm resizing to fill a div, so having a little flicker along the bottom and right edges is tolerable, and certainly much better than the whole thing flickering.

EDIT:

Here's an update of your jsFiddle with my changes applied:

jsfiddle.net/Uz5Pt/13

It seems to work better than where I'm using it in my app! You can hardly see any flashing on any newly created bits of canvas.

You could try using a double buffer. Here's a nice article on some techniques you could try:

http://www.html5rocks.com/en/tutorials/canvas/performance/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!