O'Reilly logo

JavaScript for Kids by Nick Morgan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 14. Making Things Move on the Canvas

Creating canvas animations in JavaScript is a lot like creating a stop-motion animation. You draw a shape, pause, erase the shape, and then redraw it in a new position. This may sound like a lot of steps, but JavaScript can update the position of the shape very quickly in order to create a smooth animation. In Chapter 10, we learned how to animate DOM elements. In this chapter, we’ll animate our canvas drawings.

Moving Across the Page

Let’s use canvas and setInterval to draw a square and move it slowly across a page. Create a new file called canvasanimation.html and add the following HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Canvas Animation</title>
</head>

<body>
    <canvas id="canvas" width="200" height= ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required