javascript - 如何为每个块分配一个 ID 以区分 canvas 内的块并根据该 ID 获取数据

各位开发者您好,

我是 react 和 canvas api 的新手,我想创建 10k 个特定尺寸的块(正方形),并且每个块的 ID 彼此不同。我创建了 10k 个 100 * 100 行和列的块,每个框都是 10 * 10。

  1. 现在我想要为每个框分配一个 ID,以识别我选择 onClick 并从智能合约读取数据的特定框

  2. 一旦选择了 ID,我希望能够使用输入字段选择多个框,例如,我选择了框#4,在输入字段中我必须选择宽度和高度,所以当我选择宽度 5 块编号 5 6 7 x 方向上的 8 9 也将被选中,类似地,如果我选择高度 2,则在 y 方向上再包括 4 个框。

现在,只有当该框的 value 为 false 时该框可供选择时,才会发生这些选择,无论高度和宽度如何,都没有人可以选择该框。

我不知道如何分配一个ID,请任何人都可以帮助我,这将是很大的帮助

参考网站了解我的观点:https://milliondollartokenpage.com/

Code is attached that I've done so far:

https://jsfiddle.net/ahmedzafar/d3twnfe1/1/

提前致谢:)

回答1

Canvas 对于绘制的元素没有“ID”的概念,你必须跟踪它......

但是 canvas 作为帮助我们解决这个障碍的好选择,我最喜欢的是 Path2d:

https://developer.mozilla.org/en-US/docs/Web/API/Path2D/Path2D

这是一个起点:

class Shape {
  constructor(x, y) {
    this.path = new Path2D();
    this.path.arc(x, y, 16, 0, 2 * Math.PI);
  }

  draw(ctx, pos) {
    ctx.beginPath();
    ctx.fillStyle = ctx.isPointInPath(this.path, pos.x, pos.y)? "red": "tan"
    ctx.fill(this.path);
  }
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return { x: evt.clientX - rect.left, y: evt.clientY - rect.top };
}

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

shapes = []
for (var i = 0; i < 6; i++) {
  shapes.push(new Shape(50 + i * 40, 40))
}

canvas.addEventListener('mousemove', function(evt) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  shapes.forEach(s => { s.draw(ctx, getMousePos(canvas, evt)) })
}, false);

shapes.forEach(s => { s.draw(ctx, { x: 0, y: 0}) })
<canvas id="canvas" width=500 height=150></canvas>

在该示例中,我们可以看到我使用 Path2DisPointInPath 来确定鼠标是否在元素上,并相应地更改填充颜色。

这是另一个例子,这次我们检测用户是否点击了我们的一个形状,并将一些信息输出到控制台。

class Shape {
  constructor(name, x, y) {
    this.obj = {name, x, y}
    this.path = new Path2D();
    this.path.rect(x, y, 50, 50);
  }

  draw(ctx) {
    ctx.beginPath();
    ctx.stroke(this.path);
    ctx.strokeText(this.obj.name, this.obj.x +10, this.obj.y +20)
  }
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return { x: evt.clientX - rect.left, y: evt.clientY - rect.top };
}

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

shapes = []
shapes.push(new Shape("A", 10, 10))
shapes.push(new Shape("B", 80, 10))
shapes.push(new Shape("C", 150, 10))

canvas.addEventListener('mouseup', function(evt) {
  var pos = getMousePos(canvas, evt);
  shapes.forEach(s => { 
    if (ctx.isPointInPath(s.path, pos.x, pos.y))
      console.log(s.obj)
  })
}, false);

shapes.forEach(s => { s.draw(ctx) })
<canvas id="canvas" width=300 height=100></canvas>

我的示例不是 React/NodeJs 而是...

我希望您可以轻松地将这个概念集成到您的项目中。

我有一些时间来玩你的示例,我在这里做了一些更改,有两个版本:

相似文章

python - Python 函数式编程中的弹跳球游戏

这是一款常见的街机游戏,目标是尽可能多地击中所有目标以获得最高分。每次球击中“石头”,您将获得1分,如果击中2,您将分别获得2分。如果球员未能在横杆或“杆”上接球,则比赛结束。我的任务是将这个用面向对...

随机推荐

最新文章