thesystem
thesystem

Reputation: 604

Making an object move on canvas in JavaScript

I am trying to make a simple game in JavaScript in which you move an object (circle/ball) around on canvas using arrow keys. I have spent a lot of time researching and coding, but without luck so far, so I hope you guys can help me. For now, I am simply trying to move the object/ball around using arrow keys [up, down, left, right]. Anybody able to figure out, why this doesn't work? Thank you very much in advance.

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");

canvas.width = canvas.height = 500;

//the circle
function circle() {
    ctx.beginPath();
    ctx.arc(50, 50, 25, 0, Math.PI * 2, true);
    ctx.fillStyle = "blue";
    ctx.fill();
}

circle();

//move function for going left
window.addEventListener("keydown", function(event) {
    if (event.keyCode == 37) {
      circle.x = 1;
    }
})

Upvotes: 1

Views: 3947

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

You could accomplish such movement in the following way ...

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var x = 50,
    y = 50,
    radius = 15,
    speed = 3;

function circle() {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2, true);
    ctx.fillStyle = "#07C";
    ctx.fill();
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    circle();
    requestAnimationFrame(draw);
}

draw();

window.addEventListener("keydown", function(e) {
    switch (e.key) {
        case 'ArrowUp':
            if (y > radius) y -= speed;
            break;
        case 'ArrowDown':
            if (y < canvas.height - radius) y += speed;
            break;
        case 'ArrowLeft':
            if (x > radius) x -= speed;
            break;
        case 'ArrowRight':
            if (x < canvas.width - radius) x += speed;
            break;
    }
});
canvas {
  border: 1px solid black;
}
<canvas id="mycanvas" width="200" height="200"></canvas>

apology for not giving any explanation

Upvotes: 3

Related Questions