Reputation: 133
An example here.
var context=document.getElementById("canvas").getContext("2d");
//Red Box
context.beginPath();
context.fillStyle="Red";
context.rect(10,10,50,50);
context.fill();
//Pink circle
context.beginPath();
context.lineWidth="3";
context.fillStyle="Pink";
context.arc(250,250,50,0,Math.PI*2,false);
context.fill();
context.stroke();
context.font="1.2em Verdana";
context.fillStyle="Black";
context.fillText(context.isPointInPath(35,35),35,35);
context.fillText(context.isPointInPath(250,250),250,250);
If you write without beginPath all objects detected. How to identify objects on the canvas or to omit beginPath?
Upvotes: 9
Views: 4132
Reputation: 5101
I've just read that a new addition to the canvas specification is Path() objects. Presumably these could be stored and subsequently tested and/or replayed. Could be useful. If I've understood the spec correctly.
http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#path-objects
Upvotes: 2
Reputation: 114481
If you want to use that function you need to rebuild the path every time you want to do the test (just don't call fill
or stroke
).
What I do normally instead is using my own point-in-polygon test function or my own spatial data structure if there are a lot of objects and speed is important.
Note that a canvas is just a bitmap and it doesn't store the commands you use to draw on it. That is why it cannot do the check after drawing a shape and you can test only the current path.
Once you call beginPath
the previous path geometry is discarded and what you have are only the affected pixels if you called fill
or stroke
.
May be for your case it may make sense to check the color of the canvas pixel...
Upvotes: 9