is there a way to add drag and drop in svg d3.js?

2019-08-02 07:40发布

I'm working on a layout builder in SVG and want to add drag and drop and resizable features to it. my webpage contains a main canvas(SVG) and some nested SVG's in it. I want my nested SVG's (child SVGs you can say) to be draggable. How can I do that? I searched in JQuery we have draggable and resizable API but its not working in SVG. How can I achieve it in d3.js? any help would be preferred. thanks in advance.

标签: jquery d3.js svg
1条回答
虎瘦雄心在
2楼-- · 2019-08-02 08:11

Mike Bostock's Circle Dragging example should get you started. The bare minimum, comparable to jQuery, would be:

svg.selectAll("svg").call(d3.drag().on("drag", dragged));

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

But better join the SVG elements to data objects first and then modify the data instead of the elements directly:

svg.selectAll("svg").data(elements)
  .enter().append("svg")
    .attr("x", function(d) { return d.x; })
    .attr("y", function(d) { return d.y; })
    .attr("width", function(d) { return d.width; })
    .attr("height", function(d) { return d.height; })
    .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended);

function dragstarted(d) {
  d3.select(this).raise();
}

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

function dragended(d) {
}

To account for mouse pointer offset, and to turn the drag-and-drop into a rescale operation, you'll have to fill in the drag handler functions accordingly.

查看更多
登录 后发表回答