Javascript – How to distort an image to create flag waving in the wind effect using html5 canvas

animation, canvas, css, html, javascript

Given an image, I need to create an animation of the image being distorted as though it's a flag waving in the wind, using javascript and an html5 canvas.

Bonus: I also would like to be able to export this animation as a png.

Best Solution

I've created a simple example of a flag waving in the wind. It's ugly because I draw the flag to fill the canvas (instead of leaving padding for the flag to wave into) and because I don't make any attempt at anti-aliasing. I also didn't make any attempt to provide 3D shading, which would help the effect.

I can get 64fps with a 320px wide flag in Chrome v8 on my machine. If you want to test the speed yourself, change the fps on line 59 to 1000 and uncomment lines 63 and 82; it will then output fps information every 100 frames to the console.

This won't work in IE8-, even with ExCanvas, because there is no mechanism to access individual pixel data there.

Edit: Just for fun, I've updated the sample to shade the ripples as they go through the image.

Edit2: For more fun, I added padding to the flag drawing (no more clipping) and I added a 'squeeze' factor that lets you make the right side of the flag bigger or smaller than the original (for perspective). Since it slows down the performance a little I've uploaded it as a separate sample.

                      US Flag waving in the wind (static screenshot)