有没有一种方法可以在svg d3.js中添加拖放? [英] is there a way to add drag and drop in svg d3.js?
问题描述
我正在使用SVG中的布局生成器,希望为其添加拖放和可调整大小的功能.我的网页包含一个主画布(SVG)和其中的一些嵌套SVG.我希望嵌套的SVG(可以说是子SVG)是可拖动的.我怎样才能做到这一点?我在JQuery中搜索我们有可拖动和可调整大小的API,但它在SVG中不起作用.如何在d3.js中实现?任何帮助将是首选.预先感谢.
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.
推荐答案
Mike Bostock的圆拖曳"示例一个>应该让你开始.可以与jQuery相提并论的最低要求是:
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);
}
但是最好先将SVG元素连接到数据对象,然后再修改数据而不是直接修改元素:
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.
这篇关于有没有一种方法可以在svg d3.js中添加拖放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!