Step 3
Let's make animation! Add the following snippet to script.js
file:
function draw() {
// drawing code
}
setInterval(draw, 10);
The setInterval
is a function built into JavaScript. The code above calls the draw()
function every 10 milliseconds (forever, or until we stop it).
Aside: requestAnimationFrame
An alternative approach to running the draw
method is using the window.requestAnimationFrame
. This methods tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. Here is how it will look like:
function draw() {
// drawing code
window.requestAnimationFrame(draw);
}
draw();
The requestAnimationFrame
is a more common approach to work with canvas for animations and games. To learn more about it, please refer to MDN web docs tutorial on Animation Basics.
Add the following to the draw
function:
ctx.beginPath();
ctx.rect(canvas.width / 2, canvas.height - 30, 10, 10);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
You won't notice the rectangles being repainted constantly at the moment, as they're not moving. We can make them move by changing their coordinates.
Let's refactor the code and introduce the following variables outside of the draw
function:
let x = canvas.width / 2;
let y = canvas.height - 30;
const dx = 2;
const dy = -2;
Update the command to draw a rectangle inside the draw
function:
ctx.rect(x, y, 10, 10);
Finally, update the values of x
and y
coordinates inside the draw
function:
x += dx;
y += dy;
Save your code again and try it in your browser. This works ok, although it appears that the moving object is leaving a trail behind it:
The apparent trail is there because we're painting a new rectangle on every frame without removing the previous one. Put the following statement as the first line inside the draw` method to take care of this issue.
ctx.clearRect(0, 0, canvas.width, canvas.height);
To slow down the movement and better observe it, feel free to update the time interval (set it to 100
milliseconds for instance). Notice the moving object eventually exits the canvas! We will take care of this issue later.