简体   繁体   中英

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

I have a grid of squares, in a canvas, and I am able to get the click coordinates within the canvas perfectly. I want to know how you can find the shape at those coordinate. Here is the code:

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);
    }

  }

Here is the HTML:

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

I figured it out. Since I create an array of objects containing information of each rectangle, I just use the coordinates and compare the coordinates all the square info objects using a loop, and use the index of the correct square!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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