Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 canvas - Saving paths or clip areas to reuse

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

like image 554
Tristan Avatar asked Sep 19 '11 21:09

Tristan


People also ask

Can you save a HTML canvas image?

Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image.

How do you use clips on canvas?

clip() method of the Canvas 2D API turns the current or given path into the current clipping region. The previous clipping region, if any, is intersected with the current or given path to create the new clipping region. In the image below, the red outline represents a clipping region shaped like a star.

Is HTML5 canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.

Which method is used to mask of certain areas or clear selections from the canvas?

Clipping paths A clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts of shapes.


1 Answers

It looks like it is now possible with a new path2D object.

The new Path2D API (available from Firefox 31+) lets you store paths, which simplifies your canvas drawing code and makes it run faster. The constructor provides three ways to create a Path2D object:

new Path2D();     // empty path object
new Path2D(path); // copy from another path
new Path2D(d);    // path from from SVG path data

The third version, which takes SVG path data to construct, is especially handy. You can now re-use your SVG paths to draw the same shapes directly on a canvas as well:

var p = new Path2D("M10 10 h 80 v 80 h -80 Z");

Information is taken from Mozilla official site.

like image 105
Salvador Dali Avatar answered Sep 28 '22 07:09

Salvador Dali