Avoid jumping of an SVG Text with text-anchor whil

2019-02-26 07:43发布

Here is an SVG Text with an anchor:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:200px;height:200px;">
  <text x="50" y="30" fill="red" text-anchor="start">I love SVG</text>
</svg>

Now if I write a drag function:

var dragMove = function (d,i) {
    //d3.select(this).attr("text-anchor", "null"); Does not work
    d3.select(this).attr("x", d3.event.x)
                .attr("y", d3.event.y);
};

var dragEnd = function (d,i) {
    //d3.select(this).attr("text-anchor", "start"); Does not work
};

var drag = d3.behavior.drag()
                .on("drag", dragMove)
                .on("dragend", dragEnd);

d3.select("svg")
    .select("text")
    .call(drag);

It jumps after you drag it depending to its anchor position. Is there a solution to this?

I tried setting the anchor-text to null and then re-set it again but that does not work. I do not want the user experience of dragging to change at all. Not even when the dragging finishes.

Any idea?

Here is the JSFiddle: http://jsfiddle.net/sewVr/

2条回答
放荡不羁爱自由
2楼-- · 2019-02-26 08:28

Use d3.event.dx and d3.event.dy to get the relative drag position change and apply it in your dragMove() function.

Demo here: http://jsfiddle.net/sewVr/1/

查看更多
做个烂人
3楼-- · 2019-02-26 08:41

You can do it by saving how much were the x and y offset between the place where the mouse click happened and the origin of the text element. Like here: http://jsfiddle.net/twKD9/

查看更多
登录 后发表回答