Add onclick and onmouseover to canvas element

前端 未结 4 2192
梦毁少年i
梦毁少年i 2021-01-01 22:07

I want to add an onclick, onmouseover and an onmouseout events to individual shapes in a canvas element.

I have tried doing t

4条回答
  •  清酒与你
    2021-01-01 22:29

    In short you cannot add listeners to shapes in a canvas because the shapes aren't exposed as objects. The most straightforward way to implement this is to use a a single listener on the canvas and loop through all the objects drawn in the canvas to find the correct one.

    This answer explains how to implement this using the library Raphael which also gives you a lot of other benefits.

    If you don't want to use a library this is a very short example of doing it.

    rects = [{ color : "blue", origin : { x : 10, y : 10 }, size : { width : 60, height: 60}},
             { color : "red", origin : { x : 80, y : 60 }, size : { width : 60, height: 60}}]
    
    function onClick(event) {
        var length = rects.length;
    
        for (var i = 0; i < length; ++i) {
            var obj = rects[i];
            if (event.x > obj.x && event.x < obj.origin.x + obj.size.width &&
                event.y > obj.y && event.y < obj.origin.y + obj.size.height) {
                console.log("Object clicked: " + obj);
            }
        }
    

    NOTE: If you have a lot of objects this approach could be a bit slow. This can be combated by using a 2D spatial data structure.

提交回复
热议问题