javascript - 同步绘图
问题描述
我正在做我自己的小项目,我想熟悉 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();
任何帮助表示赞赏。
解决方案
推荐阅读
- c# - 从 .json URL 获取数据 [Xamarin]
- python - 用户身份验证 is_active 错误标志在 Django 中不起作用
- jpa - 通过花时间从表中获取记录来休眠 jpa 订单
- macos - chmod 755 所有 Mach-O 可执行文件 - macosx
- swift - 添加约束后,放置在谷歌地图上的按钮消失 Xcode ios Swift
- apache - .htaccess 中的子域访问问题
- c# - 十进制是四倍精度吗?
- git - 在没有本地克隆的情况下更改 git 存储库远程的分支头?
- python - 使用带有地理定位的请求问题使用 python 进行 Webscraping
- python - Django 重命名/重构自定义用户模型