Now that we have our framework for animation we can make things a bit more fluid. Let’s use a velocity to update the positions or coordinates of each dot rather than just throwing random numbers at them. We can then adjust the velocity or rate of movement and it will be a much more natural and fluid movement. Adding to each dot a vx and vy (we’re looking at the velocity in each dimension or axis). Then we update the x and y each frame by the current velocity. This iteration we’re just applying a flat random velocity, but it will be easy to apply a force like gravity, friction or anything to this velocity and it will calculate the balls position for us. This is when physics gets fun. interactive physics animations via javascript & canvas | 10.

[cc lang=”javascript”]

$(function () {

var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;

var total_dots = 25;

var fps = 24;

canvas = $(“#canvas”)[0];

context = canvas.getContext(“2d”);

var dots = new Array();

var drag_i = -1;

var this_dot = {};

for (var i=0; i < total_dots; i++){
var this_dot = {
x: Math.random()*canvas.width,
y: Math.random()*canvas.height,
vx: Math.random()*30-10,
vy: Math.random()*30-10,
width:canvas.width,
height: canvas.height,
radius:Math.random()*20+10
};
dots.push(this_dot);
}
draw();
$("#canvas").mousedown(function (event) {
var dx, dy, dist;
for (var i=0; i < dots.length; i++){
dx = event.pageX - this.offsetLeft - dots[i].x;
dy = event.pageY - this.offsetTop - dots[i].y;
dist = Math.sqrt(dx * dx + dy * dy);
if(dist < radius) {
drag = true;
drag_i = i
clickX = dx;
clickY = dy;
continue;
}
}
});
$("#canvas").mouseup(function (event) {
drag = false;
drag_i = -1;
});
$("#canvas").mousemove(function (event) {
if(drag) {
dots[drag_i].x = event.pageX - this.offsetLeft - clickX;
dots[drag_i].y = event.pageY - this.offsetTop - clickY;
draw();
}
});
function update(){
for (var i=0; i < dots.length; i++){
if (drag_i != i){
var this_dot = dots[i];
this_dot.vy = this_dot.vy;
this_dot.vx = this_dot.vx;
this_dot.x += this_dot.vx;
this_dot.y += this_dot.vy;
if (this_dot.x > canvas.width – this_dot.radius){

this_dot.x = canvas.width – this_dot.radius;

this_dot.vx = this_dot.vx * bounce;

}

else if(this_dot.x < 0 + this_dot.radius){
this_dot.x = this_dot.radius;
this_dot.vx = this_dot.vx * bounce;
}
if (this_dot.y > canvas.height – this_dot.radius){

this_dot.y = canvas.height – this_dot.radius;

this_dot.vy = this_dot.vy * bounce;

}

else if(this_dot.y < 0 + this_dot.radius){
this_dot.y = this_dot.radius;
this_dot.vy = this_dot.vy * bounce;
}
}
}
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i=0; i < dots.length; i++){
context.beginPath();
context.arc(dots[i].x, dots[i].y, dots[i].radius, 0, Math.PI * 2, false);
context.fill();
context.closePath();
}
}
setInterval(function() {
update();
draw();
}, 1000/fps);
});
[/cc]
Follow the whole Interactive Physics Animations via Javascript & Canvas series.