当我单击画布中的向右箭头时,请有人帮助我自动移动对象。
我的代码是
if(e.keyCode == 39) {
bullet.x = +5;
setTimeout(function() {
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.drawImage(player.Image, player.x, player.y , player.width, player.height);
ctx.drawImage(bullet.Image , bullet.x , bullet.y , bullet.width , bullet.height);
}, 300);
console.log("DOWN");
}
对于向右箭头移动的对象,我需要添加什么?
答案 0 :(得分:0)
必须使用ClearReact来使函数setInterval()前进
let canvas = document.getElementById("mycanvas");
let ctx = canvas.getContext('2d');
juego();
let ev;
let x = 0;
let base_image = new Image();
base_image.src = 'https://img.icons8.com/pastel-glyph/2x/search.png';
window.onkeydown = function(e) {
this.ev = e;
}
function draw() {
if (typeof this.ev != 'undefined' && this.ev.keyCode == 39) {
x = x + 10;
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(base_image, x, 10);
}
}
function juego() {
pat = ctx.createPattern(canvas, "repeat");
window.setInterval(draw, 500);
}
canvas {
outline: black 3px solid;
}
<canvas id="mycanvas" width="150" height="150"></canvas>
要尝试按左箭头