简体   繁体   中英

d3 dragging not working correctly

I have made a script, which allows me to drag a circle in an svg element. I have a blue ball which is draggable, but when i drag to the right the ball isn't following the mouse. Instead it jumps in front of the mouse. Also i have a red ball, which i'd like to follow the blue ball when it's being dragged around with an elastic motion. JsFiddle link: http://jsfiddle.net/qnhey17f/1/

Code(Html):

<!-- I had to add the g element, because the other circle wouldn't display otherwise -->
<svg width="500" height="500" style="background-color: lightgrey; border: 1px solid black;">
    <g>
        <circle class="dragCircle" cx="50" cy="50" fill="blue" r="30" cursor="pointer">
    </g>
    <circle cx="50" cy="150" fill="red" r="30" cursor="pointer">
</svg>

Code(Js):

var drag = d3.behavior.drag().on("drag", dragMovement);
function dragMovement(d)
{
    var dX = d3.event.x;
    var dY = d3.event.y;
    d3.select(this).attr("transform", "translate(" + dX + ", " + dY + ")");
}
d3.select(".dragCircle").call(drag);

This works for me http://jsfiddle.net/qnhey17f/3/ as for the position of mouse and the blue ball:

var drag = d3.behavior.drag().on("drag", dragMovement);
function dragMovement(d)
{
    var dX = d3.event.x - 50; // subtract cx
    var dY = d3.event.y - 50; // subtract cy
    d3.select(this).attr("transform", "translate(" + dX + ", " + dY + ")");
}
d3.select(".dragCircle").call(drag);

Corrected code:

<svg>
<circle class="dragCircle" transform="translate(50, 50)" fill="blue" r="30" cursor="pointer">
</svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM