Tuesday, May 3, 2016

javascript - canvas ball physics animation


I want to animate ball in html canvas like this.


ctx.beginPath();
ctx.arc(75, 75, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();


enter image description here


start position is left top corner and ball's maximum height position is always the same


also I don't want to use javascript physics libraries


thanks



Answer



Theres a few ways to do this. Heres one way that keeps some physics like properties to make the balls look like they are bouncing realistically


var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
balls = [];


canvas.width = 600;
canvas.height = 400;

var ball = function(){
this.x = Math.random()*10;
this.y= Math.random()*400;
this.speed =(Math.random()*10)*.1;
this.force = -this.speed*10;
this.curForce = this.force;

};

ball.prototype.update = function(){
this.x +=this.speed;
this.y += this.curForce+=0.1;

if(this.y >= 400){
this.curForce = this.force;
}
};


ball.prototype.render = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,5,0,360);
ctx.fill();
};


function init(){
for(var i = 0; i < 10; i++){

balls.push(new ball());
}
tick();
};


function tick(){
ctx.clearRect(0,0,600,400);
var i = 10;
while(i--){

balls[i].update();
balls[i].render();
}

setTimeout(tick, 10);
};

init();

Live Demo 1



And heres a second way thats even easier and probably more of what you are looking for, but has no realistic physic properties to it at all.


var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");

canvas.width = 600;
canvas.height = 200;

// Ball stuffs
var x = 0;
y = 0,

angle = 0;

function drawBall(){
x+= 0.5; // this is the speed at which the ball moves to the right
y+= Math.sin(angle);
angle+=0.008; // To get exactly what you want play with this line

ctx.clearRect(0,0,600,400);
ctx.beginPath();
ctx.arc(x,y,5,0,360);

ctx.fill();

if(y>=canvas.height){
angle = -angle; // if the ball hits the bottom of the canvas reverse the angle.
}
setTimeout(drawBall, 10);
}

drawBall();​


Live Demo 2


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...