Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 current 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?

like image 757
alex Avatar asked Apr 27 '11 14:04

alex


2 Answers

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.

like image 135
Simon Sarris Avatar answered Oct 05 '22 22:10

Simon Sarris


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.

like image 37
Phrogz Avatar answered Oct 05 '22 22:10

Phrogz