Amay
Amay

Reputation: 1521

Canvas mouse event and focus

I have 2 circles and one line. The circles have a move option (u can press them and move). Mousemove event have a variable distance to calculate the distance between mouse and the circle.

The problem is, that when you move one circle to another close enough, they will join. How to avoid that? Is there an option to make some focus or something like that? Any ideas how to fix that (is it possible?)

My code:

var canvas = document.getElementById('myCanvas'),
    context = canvas.getContext('2d'),
    radius = 12,
    p = null,
    start = false;

    point = {
        p1: { x:100, y:250 },
        p2: { x:400, y:100 }
    }

function init() {
        return setInterval(draw, 10);
}

canvas.addEventListener('mousedown', function(e) {
    start = true;
});

canvas.addEventListener('mouseup', function(e) {
    start = false;
});

canvas.addEventListener('mousemove', function(e) {

    for (p in point) {
        if(start) {
            var 
                mouseX = e.clientX -10,
                mouseY = e.clientY -10,
                distance = Math.sqrt(Math.pow(mouseX - point[p].x, 2) + Math.pow(mouseY - point[p].y, 2));

            if (distance -10<= radius) {
                point[p].x = e.clientX -10 ;
                point[p].y = e.clientY -10 ;
            } 

        }
    }
});


function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.beginPath();
    context.moveTo(point.p1.x,point.p1.y);
    context.lineTo(point.p2.x,point.p2.y);

    context.closePath();

    context.fillStyle = '#8ED6FF';
    context.fill();
    context.stroke();

    for (p in point) {
        context.beginPath();
        context.arc(point[p].x,point[p].y,radius,0,2*Math.PI);
        context.fillStyle = 'red';
        context.fill();
        context.stroke();
    }
    context.closePath();
}

init();

Upvotes: 1

Views: 1357

Answers (1)

Bali Balo
Bali Balo

Reputation: 3408

Try to save which point was pressed in your mousedown event.

Like that: http://jsfiddle.net/cs5Sg/9/

In addition, it will not calculate the distance to each point every time the mouse moves so it will be faster.

Upvotes: 2

Related Questions