Targeting and identifying shapes in the canvas

ぐ巨炮叔叔 提交于 2019-12-14 03:05:55

问题


Let's say I have four different shapes rendered on a canvas from an object.

var shapes = [
  { shape1 : 'A cool Triangle', structure: triangle(40,40,40,40,40,40) },
  { shape2 : 'A cool Rectangle', structure: rect(220,220,220,220) },
  { shape3 : 'Another cool rectangle', structure: rect(140,140,140,140) }
]

Then we render using a simple for loop in our setup code(which, for brevity's sake, I won't include).

for(let shape in shapes){
// Really shouldn't be using for...in on this array for obvious reasons
  shape.structure
}

Now we have three shapes on the canvas.

I want to know if there is an inbuilt method that can identify somehow a shape on the canvas on click. So, if I click the triangle, I return 'A cool Triangle'.

In lieu of a native function to p5, I've done something to the tune of:

sketch.mousePressed = function(){
  var mouseXCoord = mouseX;
  var mouseYCoord = mouseY;
  console.log("x:" + mouseXCoord + "y:" + mouseYCoord)  
}

which will simply give me the x and y coordinates of the mouse click, and then I'd run a custom function to seek out the shape that is sitting at the clicked coordinates. Problem is, this isn't always bulletproof – in the case of triangles for example, a mouse click within it's boundary won't always return the triangle... I'd need to somehow calculate the area of the shape (which seems as though I need a custom function for), and this just seems kinda nuts.

Is there any native function that enable me to identify an element on the canvas?


回答1:


which will simply give me the x and y coordinates of the mouse click, and then I'd run a custom function to seek out the shape that is sitting at the clicked coordinates

That's exactly what you need to do. More accurately, you'd probably iterate over the shapes and check whether the clicked point was inside any of them.

Is there any native function that enable me to identify an element on the canvas?

No. And be careful with your terminology: these aren't elements like you'd find in the DOM.

Problem is, this isn't always bulletproof – in the case of triangles for example, a mouse click within it's boundary won't always return the triangle.

You need to check whether the point is inside each triangle, not its bounding box. Do a google search for "point triangle collision detection" or "point triangle intersection" for a bunch of results. This is more of a math question than it is a programming question.

You could use the collide2D library, but honestly you should probably just do the detection yourself for something as simple as this.



来源:https://stackoverflow.com/questions/46311291/targeting-and-identifying-shapes-in-the-canvas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!