最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to move a polygon in SVG programmatically? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Jan 3, 2018 at 15:51 Autumn Skye 7,53914 gold badges74 silver badges97 bronze badges asked May 29, 2011 at 4:53 BuddaBudda 18.4k35 gold badges128 silver badges211 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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.

发布评论

评论列表(0)

  1. 暂无评论