Events attached to object inside canvas

前端 未结 3 700

I have simply canvas code which draw rect on the canvas

var x=document.getElementById(\"canvas\");
var ctx=x.getContext(\"2d\");
ctx.rect(20,20,150,100);
ctx         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 07:25

    If you draw something to a canvas, the shape that is drawn is not a javascript object, but rather changes the particular state that the canvas is in. Therefore, you cannot attach an event listener to it, and should instead attach the event to the canvas itself.

    Your javascript could then check the co-ordinates of the click, and find whether or not it is inside the rectangle. Bear in mind that if you draw something on top of the rectangle or shape, the code will have to be adjusted to check the new area formed. You might also find it difficult to check the area if it is not a rectangle, but it will still be possible.

    If you want to redraw the rectangle as red, you should repaint the canvas, changing the colour of the new rectangle that you redraw (the rectangle is not an object, so you cannot change the colour directly). This would also involve repainting all the other shapes on the canvas.

提交回复
热议问题