In this post we will create an effect which mimics flowing water as follows:
Note that this effect can also be used to create the appearance of a background scrolling past such as the tree in Chicken Wings, and is used to create both the water in Entombed and the lava in Brimstone.
The concept is simple: take an image, double it in the vertical direction, and use context.drawImage to pull snapshots from it. The steps are as follows:
- Create an image called the basis image. Its width w and its height h should be the width and height of the desired canvas.
- Create a second image scrollImage of width w and height 2h. The upper half of this image is a duplicate of the basis image, and the lower half of this image is also a duplicate of the basis image.
- Declare a variable y which keeps track of the scrolling. Initialize it to 0.
- Create a function scroll() which does the following:
- Clears the canvas.
- Clips a canvas-sized rectangle out of the scrollImage at location (0,y):
- Increments y and uses modulus to ensure it is bound between 0 and the canvas height:
y %= canvas.height;
Once the scroll function is created, call it periodically within a setInterval event.