Drawing a repeating sinusoidal wave with canvas api

I’m trying to get an image to flow horizontally in a sinusoidal fashion, and repeat seamlessly when it gets to the end of its own width in relation to its canvas size.

So far, I’ve got the image repeating and waving, but there is a significant jump when the x axis needs to be reset.

I think the problem is here:

 if (x > canvasX) {
            console.log('reset!!');
            x = canvasX-imgW;
            y = sineY(x);
        }
        //draw aditional image
        if (x > (canvasX-imgW)) {
            var ax = x-imgW+dx;
            y =  sineY(ax);
            ctx.drawImage(img,ax,y,imgW,imgH);
        }

Ultimately, what happens is that the sineY of the reset x value is about 19 degrees off of what it should be at the end of its regular period where the x value is highest. However, I can’t really figure out how to adjust the bounds to make the movement seamless through the multiple periods.

Here’s the fiddle: http://jsfiddle.net/3L7Dp/

Answer

The period variable needs to be normalized based on the total distance x will move.

In this case x will go image.width so period must be:

var period = x / imgW;  //period must be a value in the range [0.0, 1.0]

This should give an usable value for cycling the image.

Modified fiddle

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *