我无法让图片在画布中移动。尝试了很多事情但失败请求帮助
var canvas = document.getElementById("mainCanvas");
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
从这里开始
var player = function(img){
x=10,
y=10,
width=20,
height=20
}
添加播放器
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
function game(){
update();
render();
}
function update(){
if(keys[37]) player.y--;
if(keys[38]) player.y++;
if(keys[39]) player.x--;
if(keys[40]) player.x++;
};
我需要知道如何让玩家移动
答案 0 :(得分:0)
我建议更改代码逻辑。首先,使用requestAnimationFrame()来注册要触发的方法,该方法仅在需要时自动呈现/更新画布。阅读基本信息here。 我不知道你的逻辑是如何实现的,你发布的源代码相当不完整,但建议你将var player更改为object而不是function(所以player.x ++会起作用):
function render() {
//your render code here
player1.draw();
requestAnimationFrame(render);
}
function Player(img){
this.x = 10;
this.y = 10;
this.height = 20;
this.width = 20;
this.img = img;
}
Player.prototype.draw = function() {
canvas.drawImage(this.img);
};
//create instance of Player
player1 = new Player(handleToYourPlayerImage);
// start it
requestAnimationFrame(render);
(别忘了将键盘处理代码添加到其中。)