Click events on complex canvas shapes without recourse to external libraries

后端 未结 1 1123
悲哀的现实
悲哀的现实 2021-01-27 15:04

I\'d like to implement click detection for multiple complex shapes on a single canvas element similar to that as realized by CanvasRenderingContext2D.isPointInPath()

1条回答
  •  悲&欢浪女
    2021-01-27 15:35

    isPointInPath accepts a Path2D object as optional first argument.

    So an easy way is to create such Path2D objects for each of your shapes.
    It can even ease your drawing operations, since fill() and stroke() also accept these objects:

    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const result = document.getElementById('result');
    
    const shape1 = new Path2D();
    shape1.moveTo(25, 25);
    shape1.lineTo(105, 25);
    shape1.lineTo(25, 105);
    
    const shape2 = new Path2D();
    shape2.moveTo(125, 45);
    shape2.lineTo(45, 125);
    shape2.lineTo(125, 125);
    shape2.lineTo(205, 45);
    shape2.closePath();
    
    // to render it
    ctx.fill(shape1);
    ctx.fill(shape2);
    
    canvas.addEventListener('mousemove', e => {
    result.textContent = `
      shape1: ${ctx.isPointInPath(shape1, e.offsetX, e.offsetY)}
      shape2: ${ctx.isPointInPath(shape2, e.offsetX, e.offsetY)}
      X: ${e.offsetX} Y: ${e.offsetY}`;
    });
    .log { display: inline-block; vertical-align: top}
    
    
    In path:
    false

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