首页 > 解决方案 > 同步绘图

问题描述

我正在做我自己的小项目,我想熟悉 javascript,我最近了解了算法,所以我想我会将两者结合起来制作一个算法可视化 Web 应用程序。不幸的是,我在绘制算法时遇到了问题。我希望它逐个更新(方块中的颜色),以便用户可以看到算法是如何工作的。我所有的尝试都导致画布在等待完成之前不会更新,然后所有方块同时被着色。这是我尝试绘制算法认为最快的路径的一个示例(因为它比整个 BFS 算法代码更容易遵循/显示此代码)

function findPath()
//returns an array of directions
path = findShortestPath([startY, startX], map);
console.log("path: " + path);
ctx.fillStyle = "cyan"
showPath(path);
}

function wait(ms) {
  var start = Date.now(),
    now = start;
  while (now - start < ms) {
    now = Date.now();
  }
  console.log("waited");
}

function showPath(instructions) {

  for (var x = 0; x < instructions.length - 1; x++) {
    wait(1000);
    if (instructions[x] == 'East') {
      startX += 1;
      ctx.fillRect(((startX * 40) + 10), ((startY * 40) + 10), 40, 40);
    } else if (instructions[x] == 'North') {
      startY = startY - 1;
      ctx.fillRect(((startX * 40) + 10), ((startY * 40) + 10), 40, 40);
    } else if (instructions[x] == 'West') {
      startX -= 1;
      ctx.fillRect(((startX * 40) + 10), ((startY * 40) + 10), 40, 40);
    } else if (instructions[x] == 'South') {
      startY += 1;
      ctx.fillRect(((startX * 40) + 10), ((startY * 40) + 10), 40, 40);
    }
  }
}
findPath();

任何帮助表示赞赏。

标签: javascriptvisualizationshortest-pathsynchronous

解决方案


推荐阅读