【问题标题】:Javascript: How to find a specific shape on a canvas based on click coordinatesJavascript:如何根据点击坐标在画布上查找特定形状
【发布时间】:2020-09-08 13:25:20
【问题描述】:

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

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>

【问题讨论】:

  • 您可以通过针对您拥有的每个形状的“命中测试”光标位置来做到这一点。正方形很简单,你只需要检测一个点和一个矩形之间的碰撞。这里有一些东西可以引导你完成它:jeffreythompson.org/collision-detection/point-rect.php
  • 谢谢,我使用您建议的技术解决了这个问题! :)

标签: javascript html angular html5-canvas


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多