【问题标题】:How can I move pieces / images from a checkerboard on Canvas using JavaScript?如何使用 JavaScript 从 Canvas 上的棋盘格中移动片段/图像?
【发布时间】:2019-12-01 20:56:50
【问题描述】:

我只使用 Canvas 和 JavaScript 代码创建一个跳棋游戏,如何移动棋盘上的棋子?

我已经将整个板子和单独的部分创建为函数,现在我的问题是在整个板上移动这些部分。我尝试了很多代码,但仍然无法处理带有事件的部分。

var pieces = [];
var InitGrid = 3;
var gridHeight = 8;
var BlackPieces = "#000000";
var WhitePieces = "#ffffff";
var canvas;
var ctx;


function Box(row, column, color) {
  this.row = row;
  this.column = column;
  this.color = color;
}

function Draw(lienzo) {

  canvas = lienzo;
  ctx = canvas.getContext("2d");


  for (var i = 0; i < InitGrid; i++) {
    for (var j = (i + 1) % 2; j < gridHeight; j = j + 2) {
      pieces.push(new Box(i, j, BlackPieces));
    }
  }

  for (var i = gridHeight - 1; i >= gridHeight - InitGrid; i--) {
    for (var j = (i + 1) % 2; j < gridHeight; j = j + 2) {
      pieces.push(new Box(i, j, WhitePieces));
    }
  }

  paintGrid();

}

function paintGrid() {

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for (var x = 0; x <= canvas.width; x += 50) {
    ctx.moveTo(x, 0);
    ctx.lineTo(x, canvas.width);
  }

  for (var y = 0; y <= canvas.height; y += 50) {
    ctx.moveTo(0, y);
    ctx.lineTo(canvas.height, y);
  }

  ctx.strokeStyle = "Black";
  ctx.stroke();

  for (var i = 0; i < pieces.length; i++) {
    paintPlayer(pieces[i], pieces[i].color);
  }


}

function paintPlayer(p, color) {
  ctx.beginPath();
  ctx.arc(25 + p.column * 50, 25 + p.row * 50, 19, 0, (Math.PI * 2), true);
  ctx.stroke();
  ctx.fillStyle = color;
  ctx.fill();
}

我希望能够通过画布对角控制碎片。

【问题讨论】:

    标签: javascript html canvas html5-canvas 2d-games


    【解决方案1】:

    您可以在画布上添加一个事件侦听器来监控pointerdown 事件。

    const colCount = 8;
    const rowCount = 8;
    const colSize = canvas.width / colCount;
    const rowSize = canvas.height / rowCount;
    
    canvas.addEventListener('pointerdown', e => {
      const col = Math.floor(e.offsetX / colSize);
      const row = Math.floor(e.offsetY / rowSize);
    
      /* If there's a piece at the given column/row,
         the user can now drag it to a new location */
    });
    

    您需要添加一个相应的pointerup 事件来找出玩家将棋子放到棋盘上的哪个单元格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      相关资源
      最近更新 更多