I’m currently implementing a 2d deformable terrain effect in a game I’m working on and its going alright but I can envision it becoming a performance hog very fast as I start to add more layers to the effect.
Now what I’m looking for is a way to possibly save a path, or clipping mask or similar instead of having to store each point of the path in the terrain that i need to draw through each frame. And as I add more layers I will have to iterate over the path more and more which could contain thousands of points.
Some very simple code to demonstrate what I’m currently doing
for (var i = 0; i < aMousePoints.length; i++)
{
cRenderContext.save();
cRenderContext.beginPath();
var cMousePoint = aMousePoints[i];
cRenderContext.arc(cMousePoint.x, cMousePoint.y, 30, 0, 2 * Math.PI, false);
cRenderContext.clip();
cRenderContext.drawImage(cImg, 0, 0);
cRenderContext.closePath();
cRenderContext.restore();
}
Basically I’m after an effecient way to draw my clipping mask for my image over and over each frame
Notice how your clipping region stays exactly the same except for its x/y location. This is a big plus.
The clipping region is one of the things that is saved and restored with
context.save()andcontext.restore()so it is possible to save it that way (in other words defining it only once). When you want to place it, you will usectx.translate()instead of arc’s x,y.But it is probably more efficient to do it a second way:
drawImagewith the in-memory canvas onto your game context. In other words:cRenderContext.drawImage(in-memory-canvas, x, y);where x and y are the appropriate location.So this way the clipping region always stays in the same place and is only ever drawn once. The image is moved on the clipping-canvas and then drawn to look correct, and then the in-memory canvas is drawn to your main canvas. It should be much faster that way, as calls to
drawImageare far faster than creating and drawing paths.As a separate performance consideration, don’t call
saveandrestoreunless you have to. They do take time and they are unnecessary in your loop above.If your code is open-source, let me know and I’ll take a look at it performance-wise in general if you want.