繁体   English   中英

Javascript:如何根据点击坐标在 canvas 上查找特定形状

[英]Javascript: How to find a specific shape on a canvas based on click coordinates

我有一个正方形网格,在 canvas 中,我能够完美地获得 canvas 内的点击坐标。 我想知道如何在这些坐标处找到形状。 这是代码:

ngOnInit(): void {

    const canvas = document.getElementById('myCanvas');
    const ctxGrid = canvas.getContext('2d');
    ctxGrid.lineWidth = 0.1;

    canvas.addEventListener('mousedown', onDown, false);

    //grid with rectangles
    for (let i = 0; i < 50; i++) {
      for (let j = 0; j < 25; j++) {
        //variables
        let x = i * 20;
        let y = j * 20;
        let l = 20, w = 20;
        //push the square info
        this.shapes.push({ x, y, l, w }) //array of objects storing the information of the rectangle
        //draw it
        ctxGrid.strokeRect(x, y, l, w);
      }
    }

    function onDown(event) {

      const rect = canvas.getBoundingClientRect()
      let cx = event.clientX - rect.left;
      let cy = event.clientY - rect.top;
      console.log(cx + ", " + cy);
    }

  }

这是 HTML:

<canvas id="myCanvas" width="1000" height="500">
</canvas>

我想到了。 由于我创建了一个包含每个矩形信息的对象数组,因此我只使用坐标并使用循环比较所有正方形信息对象的坐标,并使用正确正方形的索引!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM