admin管理员组

文章数量:1278981

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?

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?

Share Improve this question edited Nov 3, 2011 at 9:56 Keepq asked Nov 2, 2011 at 17:08 KeepqKeepq 1333 silver badges9 bronze badges 1
  • +1 for a simple, elegant, and properly pared-down test case explaining your problem. – Phrogz Commented Nov 2, 2011 at 20:25
Add a ment  | 

2 Answers 2

Reset to default 9

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 mands 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...

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/specs/web-apps/current-work/multipage/the-canvas-element.html#path-objects

本文标签: javascriptHtml5 Canvas method isPointInPath determines only the last objectStack Overflow