【问题标题】:How to make a ripple effect across a javascript canvas tilemap?如何在 javascript canvas tilemap 上产生涟漪效应?
【发布时间】:2022-11-29 08:58:33
【问题描述】:

TLDR:如何在瓷砖地图上制作一条对角线以产生波纹颜色效果

我有一张瓦片地图,比如 20x20 瓦片地图,是用 Javascript Canvas 绘制的。我想做一个波纹效果(从左上角到右下角的正方形通过对角线慢慢改变颜色)。问题是,我的瓦片地图是这样表示的:

[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
]

我不知道从哪里开始,也不知道在这样设置阵列时如何用对角线慢慢改变颜色。我可以访问每个单独的方块,我已经有一个 for 循环来单独更改每种颜色,任何线索如何做到这一点? 如果您想查看,这是我的 for 循环:

//function to visualise the tile map in a 5x5 square around the player
function draw() {
  ctx.fillStyle = 'white';
  ctx.clearRect(0, 0, 400, 400);
//start of row (y) 0 and collum 0 (x)
  let x = 0;
  let y = 0;
  for (i = 0; i < gridSize * gridSize; i++) {
    x++;
//if we are above the gridSize (20), reset collum to 0
    if (i % gridSize == 0) {
      x = 0;
    }
//if we are above gridSize (20), and we are not on row 0, increment the row
    if (i % gridSize == 0 && i > 0) {
      y++;
    }

//Color each square accordingly
    if (grid[y][x] == "Obstacle") {
      ctx.fillStyle = 'black';
    }
    if (grid[y][x] == "Goal") {
      ctx.fillStyle = 'green';
    }
    if (grid[y][x] == "Empty") {
      ctx.fillStyle = 'white';
    }
    if (grid[y][x] == "Player") {
      ctx.fillStyle = 'red';
    }
    if (grid[y][x] == "Start") {
      ctx.fillStyle = 'purple';
    }
    if (grid[y][x] == "Valid" || grid[y][x] == "Invalid" || grid[y][x] == "Visited") {
      ctx.fillStyle = 'blue';
    }

//Draw each square so that is is 400/gridSize (400/20 or 20) wide and the same height.
    ctx.fillRect((x) * 400 / gridSize, (y) * 400 / gridSize, 400 / gridSize, 400 / gridSize)
    ctx.beginPath();

//You can ignore this, it just makes borders for each tile
    ctx.rect((x) * 400 / gridSize - 1, (y) * 400 / gridSize - 1, 400 / gridSize + 2, 400 / gridSize + 2)
    ctx.stroke();
    ctx.closePath();
  }
}

TLDR:如何在瓷砖地图上制作一条对角线以产生波纹颜色效果

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    找到了解决方案,如果有人真的关心的话。我所要做的就是制作一个包含每个位置的数组,然后按顺序绘制它们。一个例子是这个 JSFIDDLE 中的函数 floodMoves():https://jsfiddle.net/6muLzn70/3/

    代码很简单:

    let arr = moveList[count2].split(",");
        x2 = Number(arr[0]);
        y2 = Number(arr[1]);
        if (count2 >= moveList.length - 1) {
          grid[y2][x2] = "Flood";
          clearInterval(int2)
        } else {
          grid[y2][x2] = "Flood";
        }
    

    全部包裹在一个间隔中。所有这一切都是利用深度优先算法可视化涟漪效应,可以在这里找到:http://gregtrowbridge.com/a-basic-pathfinding-algorithm/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多