Canvas velocity friction
HTML
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
JavaScript
// get the theory behind:
// http://nepraunig.com/wp/?p=190
// 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 = 188;
var vY = 18;
// friction
var f = 2;
// 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 the friction
// if the velocity is rather small (below 0.1), then set it to 0
if(vX > 0.1) {
vX *= f;
} else {
vX = 0;
}
if(vY > 0.1) {
vY *= f;
} else {
vY = 0;
}
// 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 velocity
vX = 8;
vY = 0;
}
ctx.fillRect(x, y, width, height);
setTimeout(animate, 33);
}
// call the animate function manually for the first time
animate();