У меня есть 4 кнопки : Up, Down,Left,Right.Которые отвечают за управление в canvas с помощью события click. Как реализовать управление с помощью кнопок W,S,A,D как в играх? Буду благодарен , если поможете.
let myGamePiece;
function startGame() {
myGameArea.start();
myGamePiece = new Component(30, 30, 20, 0, 2 * Math.PI, 'red')
}
let myGameArea = {
canvas: document.createElement('canvas'),
start: function () {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext('2d');
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function () {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
};
//Круг
function Component(x, y, radius, startAng, endAng, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.startAng = startAng;
this.endAng = endAng;
this.speedX = 0;
this.speedY = 0;
this.update = function () {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, this.startAng, this.endAng);
ctx.fill();
};
this.newPos = function () {
this.x += this.speedX;
this.y += this.speedY;
}
};
function updateGameArea() {
myGameArea.clear();
myGamePiece.newPos();
myGamePiece.update()
};
function moveUp() {
myGamePiece.speedY -= 1;
};
function moveDown() {
myGamePiece.speedY += 1;
};
function moveLeft() {
myGamePiece.speedX -= 1;
};
function moveRight() {
myGamePiece.speedX += 1;
};
let up = document.getElementById('up');
let down = document.getElementById('down');
let left = document.getElementById('left');
let right = document.getElementById('right');
up.addEventListener('click' ,(ev) => {
moveUp();
});
down.addEventListener('click', (ev) => {
moveDown();
});
left.addEventListener('click', (ev) => {
moveLeft();
});
right.addEventListener('click' ,(ev) => {
moveRight()
})