Drawing all dots as objects

$(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 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;
        dx = event.pageX - this.offsetLeft - this_dot.x;
        dy = event.pageY - this.offsetTop - this_dot.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) {
            this_dot.x = event.pageX - this.offsetLeft - clickX;
            this_dot.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();
		}
    }
});

Back to the blog post