Canvas Sine Movement
HTML
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
JavaScript
// get the theory behind:
// http://nepraunig.com/wp/?p=139
// grab the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// inital coordinates of the black square
var x = 0;
var y = 200;
// let the square move "around" this y value
var y_fix = y;
// let the square this pixels up and down the fixed y value
var range = 20;
// we will calculate the sin-values from the angle variable
// since the Math.sin function is working in radiants
// we must increase the angle value in small steps -> anglespeed
// the bigger the anglespeed value is, the wider the sine gets
var angle = 0;
var anglespeed = 0.10;
// speed of the movement
// initially 1, means it increases the x value
// if you would set it to 0, the object would move up and down
// at the same spot
var speed = 1;
// width and height of the square
var width = 10;
var height = 10;
function animate() {
// clear
// comment this clear function to see the plot of the sine movement
ctx.clearRect(0, 0, canvas.width, canvas.height);
x += speed;
// increase value for sin calculation
angle += anglespeed;
// always add to a fixed value
// multiply with range, sine only delivers values between -1 and 1
y = y_fix + Math.sin(angle) * range;
// if you would increase or decrease the range value,
// then the movement would "swing up" or "swing down"
// range += 0.10;
// if the square leaves the canvas on the right side,
// bring it back to the left side
if(x>500) {
x = 0;
// reset the range - if it has been manipulated
range = 20;
}
ctx.fillRect(x, y, width, height);
setTimeout(animate, 33);
}
// call the animate function manually for the first time
animate();