gpt4 book ai didi

svg - 如何使用 D3 move (拖放)多个形状

转载 作者:行者123 更新时间:2023-12-01 11:44:14 24 4
gpt4 key购买 nike

如何使用 d3 move (拖放)多个形状。

我尝试将一些形状放入 svg 并 move svg - 这有效但并不顺利。
This is what I got so far

<html>
<head>
<script type="text/javascript" src="d3.v3.min.js"></script>
<title>Creating SVG groups with D3.js</title>
</head>
<body>
<script type="text/javascript">

// http://tutorials.jenkov.com/svg/g-element.html

d3image = d3.select("body");

svgcanvas = d3image.append("svg:svg").attr("width", 700).attr("height", 500);

svg1 = svgcanvas.append("svg:svg").attr("x", 100).attr("y", 100);

circle1 = svg1.append("svg:circle")
.attr("cx", 40)
.attr("cy", 40)
.attr("r", 37.5)
.call(d3.behavior.drag().on("drag", move));

rect1 = svg1.append("svg:rect")
.attr("x",0)
.attr("y",50)
.attr("width",100)
.attr("height",75)
.call(d3.behavior.drag().on("drag", move));

text1 = svg1.append("svg:text")
.text("Group 1")
.attr("x", 0)
.attr("y", 70)
.style("stroke", "orange")
.style("stroke-width", 1)
.style("font-size", "150%")
.style("fill", "orange")
.call(d3.behavior.drag().on("drag", move));

function move(){
var parent = d3.select(this.parentNode);
parent.attr("x", function(){return d3.event.dx + parseInt(parent.attr("x"))})
.attr("y", function(){return d3.event.dy + parseInt(parent.attr("y"))});
};

</script>
</body>
</html>

有什么建议?

最佳答案

需要在拖动过程中更新其位置的选择上调用拖动行为。在您的代码中,您正在更新父节点的位置,这会导致奇怪的“抖动”,因为拖动位置本身是相对于父节点的。

例如,您可以替换您的 move上面的功能:

function move() {
d3.select(this)
.attr("transform", "translate(" + d3.event.x + "," + d3.event.y + ")");
}

关于svg - 如何使用 D3 move (拖放)多个形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16921777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com