Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a polygon in SVG programmatically?

Here (SVG draggable using JQuery and Jquery-svg, accepted answer) is implementation of drag-and-drop functionality to move circle. It is based on changing cx and cy attributes of moveable circle object.

How can I drag-and-drop a polygon?

How can I use any other element that doesn't have cx,cy coordinates?

Should I recalculate all object points?

I hope there is an easier way. I plan to use JavaScript+jQuery

like image 518
Budda Avatar asked Oct 10 '22 21:10

Budda


1 Answers

There is an easy way to do so without recalculatingpoints. You just have to translate the shape using the property transform. Let's say you just have any shape in your svg (in the case that I want to show you, I'm gonna use a shape element), and that you are able to move that shape only when the event mousedown, then mousemove is triggered, and that this action is ended when the mouse button is released. Then the procedure is as follows using jQuery and svg tags as selectors:

$("svg").mousedown(function(e){
    /* Getting initial coordinates of pointer */
    var GetInitCoordx = e.clientX;
    var GetInitCoordy = e.clientY;

    /* When mouse is moved while down, then applies the transformation. */
    $(this).bind("mousemove.customName", function(e){
        $("svg").find("path").attr("transform", "translate("+String(e.clientX-GetInitCoordx)+","+String(e.clientY-GetInitCoordy)+")");
    });

    /* When mouse button is released, move event is unbind */
    $(this).mouseup(function(e){
        $(this).unbind("mousemove.customName");
    );}
});

The basic idea is that. I've already designed an app using such approach, and it worked fine for me in Chrome, IE9 and Opera. Anyway, you are free to warm me if I made a mistake in the code, but what I wanted you to get is that the approach that I've used is very easy to implement.

Also, remember that you can set unique property values to your svg elements, so you can identify while selecting using the jQuery selectors.

like image 185
Jesufer Vn Avatar answered Oct 14 '22 03:10

Jesufer Vn