如何获取 canvas api Rest 上任何图像的事件点击

how get event click of the any images on canvas apiRest

我有一个 canvas,通过休息服务,我得到了一个图像列表,包括它们的路径、x - y 坐标,还有它们的高度和宽度。我正在 canvas 上绘制这些图像。 我的想法是知道如何点击它并获得一个 ID 或其他东西,让我可以通过另一个调用其余的方式查询您的个人信息 api。

我想知道执行此任务以将其调整为我的代码的概念是什么。 谢谢

只需使用点击事件并检查所有图像的 x 和 y。 假设您有一组图像,只需循环检查点击 x/y 是否大于图像 x/y 且小于图像 x/y + width/height.

由于 canvas 元素的视觉内容无法通过 dom 访问,因此您无法在 canvas.

中的特定图形元素上添加事件侦听器

不过,您可以将点击事件侦听器添加到 canvas 元素本身,并以编程方式确定在 canvas 中点击了哪个图像。这可以通过每次点击事件发生时将光标的当前位置与列表中每个图像的坐标和大小进行比较来实现。

假设您有一个包含 canvas 中所有图像的列表,如下所示:

const images = [{
   url: './imageA.png'
   x: 10,
   y: 25,
   height: 50,
   width: 50,
   onClick: (evt) => {
      // imageA.png got clicked
   }
}, {
   url: './imageB.png'
   x: 80,
   y: 50,
   height: 50,
   width: 50,
   onClick: (evt) => {
      // imageB.png got clicked
   }
}];

现在,您可以在 canvas 中侦听点击事件并手动检查是否点击了特定图像:

// get relative cursor position within canvas
const getRelativeCursorPosition = ({clientX, clientY}) => {
  const canvasBcr = canvas.getBoundingClientRect();
  const x = clientX - canvasBcr.x;
  const y = clientY - canvasBcr.y;
  
  return {x, y}
}

canvas.addEventListener('click', (evt) => {
   const cursor = getRelativeCursorPosition(evt);

   for (img of images) {
      // check if relative cursor position is within img dimensions
      if (img.x < cursor.x &&
      img.x + img.width > cursor.x &&
      img.y < cursor.y &&
      img.y + img.height > cursor.y) {
         img.onClick(evt);
    }
  }
});

在 codepen 上查看此方法的 working demo