javascript - 如何根据按下的键使图像移到一侧?
问题描述
我在画布上加载了一个图像,但是它已经复制了它并且有两个。并且图像也根本不会根据命令移动。请帮忙
let img = document.getElementById("ship");
let player = {
x: 375,
y: 550,
w: 50,
h: 50,
};
requestAnimationFrame(draw);
function draw() {
ctx.drawImage(img, 5, 5);
ctx.img(player.x, player.y, player.w, player.h);
//Draw
//Request another frame
requestAnimationFrame(draw);
}
document.addEventListener("keydown", move);
function move(event) {
if (event.code == "ArrowRight") {
player.x = player.x + 50;
}
}
解决方案
您需要使用键码才能移动,它们在这里。
down arrow 37
up arrow 38
right arrow 39
down arrow 40
将您的代码更改为以下内容,它应该可以工作。
function move(event) {
if (event.code === 39) {
player.x = player.x + 50;
}
}
不知道为什么你有两张图片,但以下几行会导致问题
ctx.drawImage(img, 5, 5);
ctx.img(player.x, player.y, player.w, player.h);
你只需要这个,
ctx.drawImage(img, player.x, player.y, player.w, player.h);
ctx.img
也不是有效的上下文函数。
推荐阅读
- sql - 将数据从舞台发送到雪花中的多列表
- mysql-python - 在本地网络上用 Python 存储 MySQLDB
- revit-api - 如何使用 Revit API 在 Revit Family 中的 Dimension 内置组中分配带有角度的参数
- django - 如何确定在 Django 中为“prefetch_related”提供哪些“关键路径”参数?
- python - 使用异常处理进行调试
- ios - 如果某些东西符合 Codable ,它会永远无法被编码或解码吗?
- woocommerce - WooCommerce 3.8 到 5.x 更新,不再接受空属性
- xamarin - 如果没有这样的数据库,如何检查 Xamarin 中是否存在 SQLite 数据库文件并创建一个新的数据库文件?
- html - How to parse addresses from website specifying class in R?
- excel - 如何在excel中每21天增加一次日期