Canvas velocity acceleration
HTML
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
JavaScript
// get the theory behind:
// http://nepraunig.com/wp/?p=178
// 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;
// speed of the movement in x- and y-direction
// actual no movement in y-direction
var vX = 1;
var vY = 0;
// acceleration of the movement
// actual no acceleration in y-direction
var aX = 0.1;
var aY = 0.9;
// 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);
// apply acceleration
vX += aX;
vY += aY;
// apply velocity
x += vX;
y += vY;
// if the block leaves the canvas on the right side
// bring it back to the left side
if(x>500) {
x = 0;
// reset the acceleration and the velocity
vX = 1;
vY = 0;
aX = 0.1;
aY = 0;
}
ctx.fillRect(x, y, width, height);
setTimeout(animate, 33);
}
// call the animate function manually for the first time
animate();