问题
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