开发者

Is it asking too much of canvas to redraw everything inside of the game loop?

I've started a Breakout game in Canvas.

At the moment, I've only coded the display of the blocks and player.

When the game needs to update itself (every 10ms or so) it will need to call draw() which is currently going to repaint the entire canvas based on the curre开发者_C百科nt state of player, blocks and ball.

Its performance is starting to become an issue.

Is it never a good idea to repaint the entire canvas per frame? Should I be altering my code to only paint the sections which are changing?


First off: Yes, altering your code to only paint the sections that are changing may help lots, but you should always be testing specific improvements with your own code as the performance of any one optimization varies by app (sometimes greatly).

But its not only drawing that can cause slowness. Make sure, for instance, that you aren't recomputing/reconstructing anything in your draw loop that never changes.

Also, if you have a lot of objects, don't set fillStyle unless you have to, which means there's an optimization to be had by setting the fill to one color, drawing all the objects of that color, and then setting the second fill color, etc.

Finally, I'd suggest writing your entire game (or most of it) and then going back and doing optimizations.

There are loads of optimizations to be had with Canvas. I've recently begun a guidebook on game-related performance enhancements, hopefully it'll be done by the year's end.


You will have to try to be sure, but I disagree with both answers here. In my simple tests, attempting to clear and redraw just particular regions of the canvas produces slightly worse performance, not better.

You can see my test here: http://phrogz.net/tmp/image_move_sprites_canvas.html

This depends on your needs, however. If you have hundreds of items that do not need to be updated and only a small portion of your canvas changes each frame, perhaps clearing and redrawing only that section will be good.


Is it never a good idea to repaint the entire canvas per frame?

No, sometimes it's a perfectly good idea

Its performance is starting to become an issue

But not then.

That said, though, your code is not that complicated and there's nothing to cause obvious massive slowdowns. How are you measuring its performance?


First I'd take all this out of init():

canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 300;
ctx = canvas.getContext('2d');
document.body.appendChild(canvas);

There's no point dealing with that every millisecond!

Secondly, look at this: http://paulirish.com/2011/requestanimationframe-for-smart-animating/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜