Interactive Physics Animations Javascript Canvas 06

Here we’re going to get more into the interactive programming on these dots. We started with one dot that was draggable. This update applies a drag/drop code to each dot object with some logic to keep track of which dot is being dragged. This is quite a bit different than accomplishing the same thing in flash. Flash lets us have visual objects, but here in javascript we have all these objects and they are drawn on the stage/canvas every “frame”. The elements once drawn really don’t have any properties. So we’re attaching mousedown, mouseup and mousemove events to the canvas. In flash we would be applying a click event to the objects themselves. On mousedown we check coordinates to see if we’ve clicked on any of the dots. We also need a variable to store which one is being clicked or dragged at the moment, and this is pretty easy since we set up earlier to have an array holding all our dots, we’ll just use the index of that dot. With mousemove we drag the dot that’s been clicked using that index value, and then mouseup we drop it. interactive physics animations via javascript & canvas | 06.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
var dots = new Array();
var drag_i = -1;

var this_dot = {};
for (var i=0; i < 5; i++){ var this_dot = { x: Math.random()*canvas.width, y: Math.random()*canvas.height, width:canvas.width, height: canvas.height, radius:25}; 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 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(); } } }); [/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.