Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
In this movie, we're going to see how to create a smooth animation using a technique known as double buffering. Double buffering is called that because all the drawing takes place on an offscreen canvas, or buffer, before it is copied to the onscreen canvas. The reason you do this is because if you have a lot of objects that are being animated, if you're just doing all the animation directly on the screen, the user might see things like flicker or other unwanted artifacts that don't happen when you draw everything offscreen first and then copy the finished frame onto the canvas.
So let's take a look at the example that we're going to build. I'm going to bring up my finished example, and you can see that what we have here is a nice nighttime sky with snowflakes of various sizes falling at various speeds and randomly drifting to the left at various rates. So this is the example that we're going to build. You can see that it's nice and smooth. There's no stuttering or anything like that. So this example is using double-buffering animation, so all the snowflakes are being animated on a canvas that you can't see off the screen, and then each frame, as it's completed, is copied onto the canvas.
So let's go ahead and build that. I'm going to open up my start point here in the editor and in the snippets and at my Double Buffer Animation, so let's copy things over. So this is just some initialization code. So here's the canvas and context that's in the page, and that's this canvas right here. But we also have variables for the buffercanvas, and this is a canvas that to we're going to create offscreen. We have an array to hold all the snowflakes, we have a timer that is used to animate each flake, and then we have a variable that keeps track of the maximum number of flakes we're going to have on the screen. So let's save.
Let's copy over the initialization function. So we copy that and we paste it. So the initialization function will get called when the document loads, and that's right here. So when the document loads, we're going to get a reference to the canvas in the context of the canvas that's in the page. And we're going to use that information to create a new buffer canvas. So you can see we're using the document's DOM right here to create a new canvas element, and then retrieve its context.
Now this canvas is not in the page; it's floating in space somewhere, but we can still use it to draw on. So once we've created the buffercanvas, we set its width and height to the same width and height of the canvas that's already in the page. Once we've initialized that, we set an interval timer that adds snowflakes to the scene over time. So every 200 milliseconds, or pretty much every fifth of a second, we'll be adding a new snowflake. Then we have a Draw function, which draws the initial setting, and then we have an animate timer which gets called every 30 milliseconds, or about every thirty-ish frames per second or so. So let's save.
Let's copy over the animation function, and the animation function is right here, paste. So the animation function follows a fairly standard pattern that you'll see throughout various animation techniques. Every time the animation function gets called which is about 30 times per second. The first thing it does is call Update function, then it calls Draw. Now Update is responsible for moving all of the animated objects on the screen.
So it's going to move each one of the snowflakes according to its speed and drift and so on. Once all the objects have been updated to their new locations, we then call the Draw function which updates the scene and copies the contents of the buffercanvas onto the onscreen canvas. So now that we have that in place, let's save, and let's copy over the supporting logic. So we have these two functions, addFlake and blank.
Let's copy that, and we'll put those in here. And let's copy over the Update and Draw functions as well, and we'll go through those and see what they do. So I'm going to put those guys down here. So as I mentioned earlier, we have Update and Draw, and now we copied over some supporting logic. The last thing we need to copy over is the logic that creates all the snowflakes.
So let's copy that over, and you can see that right here in addFlake, we have a call to a new Flake object. So I'm going to copy that because that's up here at the top, and we'll to paste that in. So here's how this works. So remember, we have a timer here that adds snowflakes to the screen gradually over time, and that's this function.
So we have an array; recall that we have an array of snowflakes. So each time this function gets called, we're going to create a new snowflake and put it in the array of snowflakes. And then once the length of the snowflake array has reached the maximum number of flakes we want, we then clear the snowflake timer so that no further flakes get added. So let's go back up and look at the initialization logic for each snowflake. So each snowflake on the screen is going to have some properties associated with it.
So we're going to multiply that by the width of the canvas. That will give us a random number that goes from zero up to the far right of the canvas, and then we'll just simply use the rounding function to round that to an n-digit number. So now we've initialized the x and y position of each snowflake, but we don't want each snowflake to just fall straight down--and that's kind of not very realistic. We want each snowflake to kind of drift a little bit. So we have a drift property, and again, we just have a little random number between 0 and 1, and we're going to add that to the x position each time to give it a little bit of a drift.
Then we have the speed at which each snowflake falls. So again, to be realistic, we want each snowflake to fall at a slightly different speed, so we have a random number between 0 and 1, times 5. That will give us a random number between 0 and 5. But we don't want zero because we don't want any snowflakes just sitting there out in space, not falling in defined gravity. So we add the number one to ensure that every snowflake at least has some speed, so this will now give us a random number between one and six.
Then we have to make the width and height of each snowflake. So we're going to give the width of the snowflake-- again, we want it to be realistic, and snowflakes are varying sizes-- so we'll have a random number between 0 and 1, times 3, so that'll give us a width between 0 and 3. But we can't have snowflakes of zero width, and we want to make sure that each snowflake is at least visible, so we'll add the number 2 to that. So now we have snowflakes of random width at least 2 and at most 5. And to make them square, we'll just set the height to be whatever the width is.
So now that we've created each snowflake, let's go back down and see what the Update function does. So remember, each time through the animate loop, we're going to update, then we're going to draw. So in the Update logic, for all of the snowflakes in the snowflake array, we need to update their position based upon their properties. So we check to see if this snowflake, if the y value is currently less than the height of the canvas; in other words, it still hasn't reached the bottom of the canvas yet. And if that's true, then we update the snowflake's position.
So we update its vertical position by adding the speed to whatever the y value is that will cause the snowflake to fall down a little bit more. If doing that has now caused the snowflake to fall off the bottom of the canvas-- in other words, the y value is now greater than the canvas height-- we reset the y value to be -5. That will reset it to be back up above the top of the canvas. So now we've updated the y position. Now we have to update the x position. Now remember, the x position gets updated because we don't want the snowflake to fall straight down; we want it to kind of drift a little bit randomly.
So each time through this animate loop, we're going to add the snowflake's drift amount to whatever its x position is. Then just like for the y position logic, we have to see if the x position is now greater than the canvas width, because it's drifted off the right side of the screen. If that's the case, we simply reset the x position of the snowflake to zero. So this is going to happen for all of the snowflakes in the array. So now when this function completes, all the snowflakes have been moved to their new position. So that means it's time for the Draw function to run.
So after Update, the Draw function is now responsible for drawing everything in its new location. So we have a save and a restore for the context--and these aren't mandatory, but it's a good practice to put them in. I just put them there in case any drawing comes before or after this particular function, if I have a complex animation that I'm working on. The first thing we do is call the blank function, and the blank function-- let's just scroll back up--all this does is draw our night sky. So we draw the background first with a nice deep purplish color, and we fill the rectangle on the buffercanvas, starting at the upper left down to the lower right.
And again, you can see that all the drawing is taking place on the offscreen buffercanvas, not on the onscreen one. So we just draw the background, and then we draw all the snowflakes. So once again, we have a loop that goes across the entire snowflake array, and for each one of the snowflakes, we set the fillStyle of the canvas on the buffercanvas to be white. And then again, on the buffercanvas, we just fill each rectangle represented by each snowflake.
So we have the x and y position and the width and the height of each snowflake. So we do that for all 200 flakes. Then when we've drawn everything to the buffercanvas, we copy the entire rendered image, this frame, from the buffercanvas onto the canvas that's on the screen. So we do that using the drawImage function that's on the onscreen canvas to copy the source, which is the buffercanvas. And again, we copy from the upper-left corner, all the way to the lower right.
So let's go ahead and save, and let's try it out. You can see now that we've got snowflakes beginning to fill the sky, and we've got a little drift going on, right? Some of them are drifting, some of them are falling at different a different speeds. So now let's get little bit fancy. Now let's add a clipping region, and remember, we learned about clipping regions earlier. So let's go back to the code. So what we're going to do now is scroll down here, and we're going to create a clipping region. I'm going to copy this and I'm going to paste it back in here.
So remember that clipping paths define an area outside of which drawing does not take place, and inside of which drawing shows through. So we're going to create a clipping region by calling the beginPath function, again, on the buffercanvas--all the drawing takes place in the buffercanvas. So we fill the entire buffercanvas with a black rectangle, starting at the upper left and going to the lower right. Then we draw an arc, and the arc is going to be drawn at the middle of the buffercanvas, so we divide the width by 2, the height by 2.
That gets at the center. We're going to give the arc a radius of 40% of whatever the canvas height is. So it's going to reach 40% in all directions. And since the radius is half the diameter, this will give us a circle of 80% of the canvas's height. And then finally we call clip which tells the canvas, only draw in the visible area which is represented by that circle. So let's save and let's see what this does. Let's refresh. Now we have a circle.
It's kind of like looking through a telescope, right? So now the snowflakes are only visible within the circular area. They're still being drawn out here. You just can't see it because the clipping region is precluding that from happening. But the effect that we've created is looking at a snowfall through say a telescope. That's our finished example. So in this movie, we've seen how to create smooth animation using a technique known as double buffering. And for good measure, we added a clipping region to clip the animation to a visible area, providing a nice nighttime snowfall effect.
Get unlimited access to all courses for just $25/month.Become a member
61 Video lessons · 96931 Viewers
56 Video lessons · 110616 Viewers
71 Video lessons · 79438 Viewers
131 Video lessons · 38120 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.