Suneth Kalhara
Suneth Kalhara

Reputation: 1221

HTML5 Canvas Drawing drag and Drop

I have example for HTML 5 circle drawing as below

https://i.sstatic.net/SVPO9.jpg

Here is the drawing script for this (HTML5 and jQuery)

http://jsfiddle.net/eGjak/275/

$.each(circles, function() {
   drawCircle(this);
   drawLine(mainCircle, this);
});

I need to upgrade this to drag and drop (the users can drag the children circles around the main circle with line)

How can I do this using html5,css3,jQuery?

Upvotes: 1

Views: 4814

Answers (1)

dansch
dansch

Reputation: 6267

http://jsfiddle.net/eGjak/503/

You have to find the local x and y on the canvas, then calculate the distance ( think pythagorean theorem, aSquared + bSquare = cSquared ), and see if the distance is less than the radius of the circle( aka mouse is within the circle )

Add this code after the code you currently have

var focused_circle, lastX, lastY ; 

function test_distance( n, test_circle ){  //see if the mouse is clicking circles
    var dx = lastX - test_circle.x,
    dy = lastY - test_circle.y;

    //see if the distance between the click is less than radius
    if( dx * dx + dy * dy < test_circle.r * test_circle.r  ){
        focused_circle = n;
        $(document).bind( 'mousemove.move_circle' , drag_circle );
        $(document).bind( 'mouseup.move_circle' , clear_bindings);
        return false; // in jquery each, this is like break; stops checking future circles
    }
}
$('#cv').mousedown( function( e ){
    lastX = e.pageX - $(this).offset().left;
    lastY = e.pageY - $(this).offset().top;
    $.each( circles, test_distance );
});

function drag_circle( e ){
    var    newX = e.pageX - $('#cv').offset().left,
        newY = e.pageY - $('#cv').offset().top;

    //set new values
    circles[ focused_circle ].x += newX - lastX;
    circles[ focused_circle ].y += newY - lastY;

    //remember these for next time
    lastX = newX, lastY = newY;

    //clear canvas and redraw everything
    ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
    drawCircle(mainCircle);
    $.each(circles, function() {
        drawCircle(this);
        drawLine(mainCircle, this);
    });

}

function clear_bindings( e ){ // mouse up event, clear the moving and mouseup bindings
    $(document).unbind( 'mousemove.move_circle mouseup.move_circle' );
    focused_circle=undefined;
}

There are other ways to do this and ways to save on speed, though this should do the trick.

Upvotes: 2

Related Questions