The Wavelength
The Wavelength

Reputation: 2914

Drawing to images/textures in html5

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.

Upvotes: 2

Views: 277

Answers (1)

Marc Baumbach
Marc Baumbach

Reputation: 10473

I'd suggest looking into the context.createPattern method. You can dynamically create a new canvas and draw your complex image on it. After you're done drawing once, you can call context.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 the context.fillStyle to be your pattern and fill in a rectangle that fits your pattern. Here's some generalized code:

// Only do this once per unique snake, not per frame
var patternCanvas = document.createElement("canvas");
// Set the size to be the minimum size to draw your snake on
patternCanvas.width = 100;
patternCanvas.height = 100;
// code that draws snake onto patternCanvas here
// ...

// Create the pattern
var pattern = patternCanvas.getContext("2d").createPattern(patternCanvas, "no-repeat");

// Using your real canvas that's drawing every frame
var realContext = realCanvas.getContext("2d");
realContext.save();
realContext.translate(50, 80); // x, y coordinates of where you want to draw your snake
realContext.fillStyle = pattern;
realContext.fillRect(0, 0, 100, 100); // The last two parameters are your width and height of your snake pattern
realContext.restore();

Notice that createPattern can take an entire canvas object and you never need to append the patternCanvas to 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. Each save/restore and modification to the context will 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/.

Upvotes: 3

Related Questions