Creating SVG text with d3.js

I want to make the text in the d3 render draggable for use in the editor. I started playing with examples ( http://bl.ocks.org/mbostock/4063550 ). When I add dragbeheavier to a text element, I can tell from ChromeDevTools that something is being dragged, but there is no visual representation. I also tried to do this using the jQuery UI, which didn't work either. What have I missed and is it possible to do this?

+5
source share
2 answers

You can use drag.behaviour to add drag and drop events to elements.

1) Create a function to handle the drag event (of type d3.event ):

function dragmove(d) {
    d3.select(this)
      .style("top", ((d3.event.sourceEvent.pageY) - this.offsetHeight/2)+"px")
      .style("left", ((d3.event.sourceEvent.pageX) - this.offsetWidth/2)+"px")
}

2) Create a drag and drop behavior using the above function as a handler:

var drag = d3.behavior.drag()
    .on("drag", dragmove);

3) Bind it to an element or set of elements, using .calld3 to select:

d3.select("body").append("div")
    .attr("id", "draggable")
    .text("Drag me bro!")
    .call(drag)

Try: http://jsfiddle.net/HvkgN/2/

Here is the same example adapted for the svg text element :

function dragmove(d) {
    d3.select(this)
      .attr("y", d3.event.y)
      .attr("x", d3.event.x)
}

var drag = d3.behavior.drag()
    .on("drag", dragmove);

d3.select("body").append("svg")
    .attr("height", 300)
    .attr("width", 300)
    .append("text")
        .attr("x", 150)
        .attr("y", 150)
        .attr("id", "draggable")
        .text("Drag me bro!")
        .call(drag)
+11
source

The best way to add drag and drop to an SVG element is to use a translation transform that moves the moveable element around. Combine this with a drag event handler that uses d3.event.dx and d3.event.dy to track mouse movement.

var transX = 0;
var transY = 0;
var theElement = d3.select('svg#xyz text.blahblah').attr('transform', "translate(" + transX + ", " + transY + ")");

var repositionElement = function(data) {
    transX += d3.event.dx;
    transY += d3.event.dy;
    theElement.attr('transform', "translate(" + transX + ", " + transY + ")");
};

var addDragging = function (element) {
    element.call(d3.behavior.drag().on('drag', repositionElement));
};

addDragging(theElement);

, x/y , , <g> , , , !

+2

All Articles