$(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 = width / 2;
    y = height / 2;
    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.fill();
    }
});

Initial source code from Keith Peters | Bit-101

Back to the blog post