html5 canvas clicking on bezier path shape detection

前端 未结 3 1610
眼角桃花
眼角桃花 2021-02-15 13:51

I have a canvas with some irregular shape drawings in it, and I would like to have a feedback when someone clicks on a specific one?

I\'ve been looking everywhere for th

3条回答
  •  情话喂你
    2021-02-15 14:23

    This can be achived by using Path2D.

    var div = document.getElementById("result");
    var canvas = document.getElementById("canvas");
    
    var ctx = canvas.getContext("2d");
    
    var path1 = new Path2D();
    path1.rect(10, 10, 100, 100);
    path1.closePath();
    ctx.stroke(path1);
    
    var path2 = new Path2D();
    path2.moveTo(220, 60);
    path2.arc(170, 60, 50, 0, 2 * Math.PI);
    path2.closePath();
    ctx.stroke(path2);
    
    var path3 = new Path2D("M230 10 h 80 v 80 h -80 Z");
    ctx.fill(path3);
    path3.closePath();
    
    $('canvas').click( function(event) 
    {
      div.innerHTML = "";
      
      var x = event.pageX;
      var y = event.pageY;
    
      if (ctx.isPointInPath(path1, x, y))
        div.innerHTML = "Path1 clicked";
    
      if (ctx.isPointInPath(path2, x, y))
        div.innerHTML = "Path2 clicked";
      
      if (ctx.isPointInPath(path3, x, y))
        div.innerHTML = "Path3 clicked";
    });
    
    
      
      

提交回复
热议问题