gpt4 book ai didi

javascript - 拖动 SVG 元素时的 d3.js 占位符图形

转载 作者:行者123 更新时间:2023-11-28 19:11:13 25 4
gpt4 key购买 nike

我正在为查询语言创建一个可视化编辑器。我有 3 个不同的 SVG 矩形元素(例如 A->Operators、B->Some_Objects、C->Drawing Canvas)。我想将元素从 A、B 拖动到 C。如果用户将元素从 A/B 拖动到 C,则应在 C 中绘制相同的元素,并且它也必须出现在 A/B 中。同时,如果用户没有将元素放入 C 中,则它不应该执行任何操作。

为了实现这一点,我尝试使用占位符技术(就像在 jQuery UI 中一样)。但我找不到怎么做。谁能帮我这个?

这是我迄今为止创建的用户界面。

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="js/live.js"></script>
<script src="js/d3.v3.min.js"></script>

</head>
<body>

<svg width="1024" height="768" style="background-color: #204d74">
<!--<g>-->
<rect x="10" y="20" height="250" width="300" style="fill: #080808"></rect>
<rect class="drg" x="12" y="22" height="50" width="50" style="fill: #f0ad4e"></rect>
<!--</g>-->
<rect x="10" y="280" height="250" width="300" style="fill: #080808"></rect>
<rect class="drg" x="12" y="282" height="50" width="50" style="fill: #f0ad4e"></rect>


<rect x="320" y="20" height="510" width="690" style="fill: #080808"></rect>
</svg>

<script>
function move() {
d3.select(this)
// .attr("transform", "translate(" + d3.event.x + "," + d3.event.y + ")");
.attr('x', d3.event.x - parseInt(d3.select(this).attr("width")) / 2)
.attr('y', d3.event.y - parseInt(d3.select(this).attr("height")) / 2)
;
this.parentNode.appendChild(this);
}
d3.selectAll(".drg").style("fill","red").call(d3.behavior.drag().on('drag', move).origin(function() {
var t = d3.select(this);
return {x: t.attr("x"), y: t.attr("y")};
}).on('dragend', function(d){
console.log('end')


})

)


</script>

</body>
</html>

最佳答案

在dragEnd时,您必须找到当前的鼠标坐标,并根据它克隆当前拖动的元素并重置原始元素的x和y位置。

已创建 jsFiddle来展示它。看看吧

    .on('dragend', function(d){
var elem = d3.select(this);
elem.attr("x",elem.attr("initial-x"));
elem.attr("y",elem.attr("initial-y"));
console.log(elem.attr("x"));
var mouseCoordinates = d3.mouse(this);
if(mouseCoordinates[0] > 320) {
//Append new element
d3.select("svg").append("rect")
.classed("drg", true)
.attr("width", 50)
.attr("height", 50)
.attr("x", mouseCoordinates[0])
.attr("y", mouseCoordinates[1])
.style("fill", "green");
}
})

关于javascript - 拖动 SVG 元素时的 d3.js 占位符图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30689901/

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