By Stephen Bucaro
This example shows you how to make an image of a flag appear to wave in the wind. Of course the
first thing you need is an image of a flag. This example is designed to display images that
are around 300 pixels wide. That's because the image will be displayed in an HTML5 canvas
element, the code for which is shown below.
<canvas id="mycanvas" width="400" height="400"></canvas>
Of course you could edit the canvas element and the code to display any size flag that you wish.
You would place this canvas element in the body section of your webpage where you want the flag
section of your webpage.
var pattern = new Image();
pattern.src = "united_kingdom.png";
var ph = pattern.height;
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var iw = pattern.width;
var ih = pattern.height;
ctx.clearRect(0, 0, 400, 400);
if(ph <= 0)
ph = ih;
ph -= 20;
for(var x = 0; x < iw; x++)
// 8 = height of wave, 20 = frequency, 38 = vertical offset
var y = 8 * Math.sin((x + ph)/20) + 38;
ctx.drawImage(pattern, x, 0, 1, ih, x, y, 1, ih);
The first thing you need to do in this code is enter a link to your flag image, in quotes, where it
says pattern.src =. If the image is in the same directory as your webpage, this would simply
be the file name of your image.
The code works by setting up an interval timer that calls the drawShape function every
500 milliseconds. Of course you can edit the time interval to make the flag wave at any speed that you wish.
The drawShape function first clears the previous image from the canvas, then it calculates a phase value for
this particular image draw. It then runs through the pixel width of the image, setting the height of each
pixel row using the Math.sin function.
In the line var y = 8 * Math.sin((x + ph)/20) + 38;, 8 sets the height of the wave, 20 sets the
frequency of the wave, and 38 sets the vertical offset of the flag image within the canvas element.
passing a different phase value to the horizontal pixel locations in the loop is what makes the flag wave.
The last thing you must do is call the animate function by placing the code shown below in the
webpage's body tag.
That's all there is to it, now you can easily have your favorite flag waving on your webapge.
More Java Script Code:
• Code to Block the Ad Blockers
• How to Disable the Browser Back Button
• Using the Java Script Array Object
• Synchronous and Asynchronous Script Loading
• Submit Forms Without CGI
• HTML5 Canvas lineCap and lineJoin Attributes