我试图让图片的位置在到达某个位置时重置,我认为
if(x == 557 && y == 533){
x = 300;
y = 300;
};
},1000);
语句会重置x和y坐标,但我错了......
var canvas = document.querySelector("#myCanvas");
var context = canvas.getContext("2d");
var canvasWidth = context.canvas.width, canvasHeight = context.canvas.height;
var x = 300;
var y = 300;
trash();
mrTrumpet();
function trash(){
var trsh = new Image();
trsh.src = "trash.png";
trsh.onload = function(){
context.drawImage(trsh, 559, 550);
};
};
function mrTrumpet(){
var img = new Image();
img.src = "character.png";
img.onload = function(){
context.drawImage(img, x, y);
};
};
function move(e){
if(e.keyCode==68){x++};
if(e.keyCode==65){x--};
if(e.keyCode==87){y--};
if(e.keyCode==83){y++};
canvas.width=canvas.width;
trash();
mrTrumpet();
};
setInterval(function(){
console.log("x = " + x + ", y = " + y);
},1000);
setInterval(function(x, y){
if(x == 557 && y == 533){
x = 300;
y = 300;
};
},1000);
document.onkeydown = move;
答案 0 :(得分:0)
第二次setInterval
来电中的参数会影响您的全球x
和y
值。
尝试:
setInterval(function() {
if(x == 557 && y == 533){
x = 300;
y = 300;
};
}, 1000);
此外,您可能想要独立检查这些值,以免有人将图像WAY移动到RIGHT或WAY到BOTTOM。
setInterval(function(){
if (x == 557) x = 300;
if (y == 533) y = 300;
}, 1000);
当图像到达“边缘”时,它会将图像重置为左/上。