По нажатию на кнопку квадрат изменяет позицию. Как сделать это перемещение плавным?
Может как то с помощью requestAnimationFrame()
или setInterval()
?
Сам код:
let canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
w = canvas.width = 200,
h = canvas.height = 200,
opts = {
w: 80,
h: 80,
x: 0,
y: 0
};
ctx.fillStyle = 'blue';
ctx.fillRect(opts.x, opts.y, opts.w, opts.h);
document.onkeydown = control;
function control() {
let speed = 20;
ctx.clearRect(opts.x, opts.y, opts.w, opts.h)
if(event.keyCode == 38) { // up
opts.y -= speed;
}
if(event.keyCode == 40) { // down
opts.y += speed;
}
if(event.keyCode == 37) { // left
opts.x -= speed;
}
if(event.keyCode == 39) { // down
opts.x += speed;
}
ctx.fillRect(opts.x, opts.y, opts.w, opts.h)
}
#canvas {
border: 1px solid;
}
<canvas id="canvas"></canvas>