簡體   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