Is there a native way to address a non-rectangle object on canvas in js?

后端 未结 1 1990
悲哀的现实
悲哀的现实 2020-12-16 08:28

I\'ve created a grid of several distorted rectangles made with Bezier curves. Each rectangle has its own color on the picture.

Let\'s say, I want to add hover effect

相关标签:
1条回答
  • 2020-12-16 08:49

    Yes you can use isPointInPath(Path2D, x, y) method.

    Note that if you don't use the Path2D object, you can also call it just with isPointInPath(x, y), but then it will check on the currently being drawn path (declared with beginPath()).

    var ctx = canvas.getContext('2d');
    var myPath = new Path2D();
    myPath.bezierCurveTo(50, 100, 180, 10, 20, 10);
    myPath.lineTo(50, 100);
    
    function draw(hover) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = hover ? 'red' : 'green';
      ctx.fill(myPath);
    }
    
    canvas.onmousemove = function(e) {
      var x = e.clientX - canvas.offsetLeft,
        y = e.clientY - canvas.offsetTop;
      var hover = ctx.isPointInPath(myPath, x, y)
      draw(hover)
    };
    draw();
    <canvas id="canvas"></canvas>

    0 讨论(0)
提交回复
热议问题