Thus far, we’ve been doing lot of setup and it hasn’t been very visually exciting. Now we start the fun stuff! Adding motion! Before we just has a draw function, but now we’ll add a function that will control the animations and we’ll also need a way to execute code repeatedly over a period of time. We’ll use a setInterval function to call first update and then draw multiple times a second and this will give the essence of animation! Here we’re just adjusting the coordinates of each of the dots every time the update function is fired, which happens to be every 100 milliseconds, or 10 times a second. interactive physics animations via javascript & canvas | 08.
[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;
var total_dots = 25;
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,
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.x += Math.random() * 10 - 5;
this_dot.y += Math.random() * 10 - 5;
}
}
}
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();
}, 100);
});
[/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.