In the last section, we look at how we could make a simple square appear. But how do we animate something like that? What if I wanted the square to move left and right? What about up and down? What would you do?
We might try something like this:
<html>
<head>
<title>Canvas</title>
</head>
<style>
#myCanvas{
border:black;
border-style: solid;
border-width: 2px;
}
</style>
<body>
<canvas id="myCanvas" height="600" width="800"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = 50;
var y = 50;
ctx.fillStyle = "#0000FF";
drawSquare();
setInterval(update, 1000);
function update()
{
drawSquare();
}
function drawSquare()
{
ctx.fillRect(x, y, 20, 20);
}
</script>
</body>
</html>
How will you make the blue square move up and down? What will you put in the update method?
Did you get it to move up and down? What about left and right? Yes? Great!
Not that kind of streaking! Get your head out of the gutter!
Now, as you can see, this does draw, but we have a problem. It’s a streaking problem. So, we need to refresh the background and then draw our square to the screen. In p5js or processing, you can say background
and provide a color like black, but here you have to call clearRect
, which essentially removes all elements from a rectangle. It looks like this:
ctx.clearRect(0,0,800,600);
So, where should the clearRect
function go?
Did you get the screen to clear and then draw? Yes? Excellent job!
There is still something not quite right. It’s jerky. So, to smooth things out, we need to create a framerate so that it refreshes the screen nicely. So, if you divide the time you have as your interval (in this case 1000), by the framerate you want, you will get nice smooth movement, and the final code looks like this:
setInterval(update, 1000/60);
Where should we put our setInterval so that the square moves smoothly?
Did you get it? Yes? Great work!
What about if I want to move something on the screen with keyEvents? Go on, and you will find out!