When I click the arrow keys (37, 38, 39, and 40) the variables of x and y change yet the position of the square given by ctx.fillRect(x, y, 100, 100); does not change. How come? And is there any solution?
<!DOCTYPE html>
<html>
<body>
<canvas id="canvasSpace" width="1460" height="710" style="border:2px solid #000000;"></canvas>
<script>
const canvas = document.getElementById("canvasSpace");
const ctx = canvas.getContext("2d");
let x = 735, y = 360
ctx.fillRect(x, y, 100, 100);
function moveLeft() {x -= 10;}
function moveUp() {y += 10;}
function moveRight() {x += 10;}
function moveDown() {y -= 10;}
function log() {
alert("x = " + x)
alert("y = " + y)
}
document.addEventListener('keydown', function(event) {
if (event.keyCode == 37) {moveLeft();}
if (event.keyCode == 38) {moveUp();}
if (event.keyCode == 39) {moveRight();}
if (event.keyCode == 40) {moveDown();}
if (event.keyCode == 13) {log();}
});
</script>
</body>
</html>
I added the log function to trigger when the enter key (13) was pressed to make sure the variables change. Yet this doesn’t appear to be the problem as the variables do change.
2
Answers
You aren’t calling fillRect again after you change the variables.
The issue is because you don’t re-draw the canvas after you change the
x
andy
values.You will also need to clear the canvas again before you re-draw it, otherwise the previous rect will still be visible.
Here’s a working example, with the logic for key bindings made more succint:
Note that the canvas size and starting
x
/y
values were only changed in the example to make it fit in to the snippet editor better.