This iteration really isn’t that big, but I figured baby steps may be the way to go here. We’re just giving the first circle a random position. The other dots are positioned relative to the first one still. interactive physics animations via javascript & canvas | 03.
[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;
canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
width = canvas.width;
height = canvas.height;
x = Math.random()*canvas.width/5;
y = Math.random()*canvas.height/5;
draw();
$(“#canvas”).mousedown(function (event) {
var dx, dy, dist;
dx = event.pageX – this.offsetLeft – x;
dy = event.pageY – this.offsetTop – y;
dist = Math.sqrt(dx * dx + dy * dy);
if(dist < radius) {
drag = true;
clickX = dx;
clickY = dy;
}
else {
drag = false;
}
});
$("#canvas").mouseup(function (event) {
drag = false;
});
$("#canvas").mousemove(function (event) {
if(drag) {
x = event.pageX - this.offsetLeft - clickX;
y = event.pageY - this.offsetTop - clickY;
draw();
}
});
function draw() {
context.clearRect(0, 0, width, height);
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2, false);
context.arc(x*2, y*2, radius, 0, Math.PI * 2, false);
context.arc(x*3, y*3, radius, 0, Math.PI * 2, false);
context.arc(x*4, y*4, radius, 0, Math.PI * 2, false);
context.arc(x*5, y*5, radius, 0, Math.PI * 2, false);
context.arc(x*6, y*6, radius, 0, Math.PI * 2, false);
context.fill();
}
});
[/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.