Hi, i’m trying to move a square in a canvas with javascript.
I wanted to create a loop function that adds 3 pixel each second , but when i run my code the square doesn’t move.
I’m new to javascript , this is my code:
Javascript
window.onload = function() {
var square = {
x: 100,
y: 100,
width: 30,
height: 30
};
var canvas = document.getElementById("game");
ctx = canvas.getContext('2d');
ctx.fillStyle = "#FF0000";
ctx.fillRect(square.x, square.y, square.width, square.height);
function loop () {
square.x += 3;
square.y +=1;
}
window.requestAnimationFrame(loop);
}
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts/script.js" ></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<title> Prove con i canvas </title>
</head>
<body>
<center>
<canvas id="game" width="400px" height="400px"></canvas>
</center>
</body>
</html>