Add onclick and onmouseover to canvas element

前端 未结 4 2222
梦毁少年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:16

    Added a more up-to-date answer: since this question was posted there are now two new techniques that can be used to detect local clicks in a canvas element:

    • Path2D: Paths can be stored on separate Path2D objects and checked using isPointInPath()
    • addHitRegion: integrates with the event system which will allow you to check the event object itself of regions

    Path2D example

     var path1 = new Path2D();
     path1.rect(x1, y1, w, h);    // add sub-path to Path2D object
    
     var path2 = new Path2D();
     path2.rect(x2, y2, w, h);    // add sub-path to Path2D object
    
     // now we can iterate through the objects to check which path we
     // clicked without the need to rebuild each path as we did in the past
     if (ctx.isPointInPath(path1, x, y)) { ... }
    

    Read more about Path2D here. A polyfill exists as well.

    addHitRegion example

    // define a region using path
    ctx.beginPath();
    ctx.rect(x, y, w, h);
    ctx.addHitRegion({id: "test"});
    
    // now we can check in the event if the region was hit by doing:
    canvas.addEventListener("mousemove", function(event){
      if(event.region) {
        // a region was hit, id can be used (see specs for options)
      }
    });
    

    Read more about addHitRegion() here.

    Note that it is still a bit early, both Firefox and Chrome supports this enabled via flags, other browsers will hopefully follow suit.

提交回复
热议问题