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.
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.
Learn more at amazon.com