The situation: I’m creating a game where every player has its snake.
The problem: Under special circumstances, a players snake could be of more than thousand arcs. I redraw the canvas on every tick (I try to get 60fps). Now, because there are too much arcs to draw, it gets very slow.
My idea: Draw the snake of every player to an image/texture, and only redraw the whole image for each player on the canvas.
My question: Is this possible? When yes, what do I have to search for? I’m not that experienced in game development.
I’d suggest looking into the
context.createPatternmethod. You can dynamically create a new canvas and draw your complex image on it. After you’re done drawing once, you can callcontext.createPattern(dynamicCanvas, 'no-repeat')and then keep a reference to that pattern around. Then anytime you want to draw that snake, translate your context to the appropriate location and set thecontext.fillStyleto be your pattern and fill in a rectangle that fits your pattern. Here’s some generalized code:Notice that
createPatterncan take an entire canvas object and you never need to append thepatternCanvasto a DOM object, so it acts like a back-buffer.When drawing your patterns, try to draw them all within the same
save/restore. Just keep translating and filling rectangles. Eachsave/restoreand modification to thecontextwill slow you down, so you want to make sure you are batching calls as much as possible.There can be any number of reasons for why Canvas may be drawing slow, so I’d recommend following some of the ideas mentioned at http://www.html5rocks.com/en/tutorials/canvas/performance/.