【问题标题】:d3js drag a text from html DOM and add it to SVG on dropd3js 从 html DOM 中拖动文本并将其添加到 SVG 中
【发布时间】:2017-07-20 18:07:49
【问题描述】:

当我学习 d3js 时,我正在尝试制作一个小程序,其中有(太阳系中的行星)作为 HTML DOM 中的文本,并且在圆圈(太阳)周围有椭圆(环)。我需要能够拖动文本,并且当它们被放下时,它应该识别出哪个椭圆并附加到组中。目前,它不需要检查位置是否正确,只需要在文本落入圆圈时附加一个圆圈。

我查看了一些 Jquery UI 和其他示例,但我在这个问题上运气不佳。

var svg = d3.select('body')
  .append("svg")
  .attr("id", "program")
  .attr("height", 500)
  .attr("width", 500);

var sun = svg.append("circle")
  .attr("cx", 250)
  .attr("cy", 250)
  .attr("r", 25)
  .attr("fill", "orange");

var mercg = svg
  .append("g")
  .attr("id", "mercury")
  .append("ellipse")
  .attr("class", "droppable")
  .attr("cx", 250)
  .attr("cy", 250)
  .attr("rx", 55)
  .attr("ry", 45)
  .attr("fill", "none")
  .attr("stroke", "black");

var venus = svg
  .append("g")
  .attr("id", "venus")
  .append("ellipse")
  .attr("class", "droppable")
  .attr("cx", 250)
  .attr("cy", 250)
  .attr("rx", 85)
  .attr("ry", 65)
  .attr("fill", "none")
  .attr("stroke", "black");

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

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

function dragend(d) {
  // Here, How do i find on what ring the item was dropped?
  // I want the circle to be on the selected ring group
}

var ex = svg.append("circle")
  .attr("transform", 'translate(0,0)')
  .attr("cx", 279)
  .attr("cy", 212)
  .attr("r", 10)
  .attr("fill", "blue")
  .call(drag);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="mySidenav" class="sidenav">
  <ul>
    <li draggable="true" ondragstart="drag()" class="draggable"> Mercury</li>
    <li draggable="true" class="draggable">Venus </li>
  </ul>
</div>

最后,我正在寻找看起来像最终生成的图像的东西。

【问题讨论】:

    标签: javascript jquery html d3.js svg


    【解决方案1】:

    我的solution

    您可以将 html 拖放到 svg 并找到放置目标。现在您可以添加if 语句来检测目标是否为椭圆。您还可以使用opacity 0 和更宽的stroke-width 参数为每​​个现有椭圆添加额外的椭圆,以避免像素搜索。

    更新:new fiddle 您可以将 HTML 元素拖放到 svg 轨道上,并且会附加新的圆圈(如果您将行星名称放在其轨​​道上)

    【讨论】:

    • 你知道为什么我之前的代码在删除项目时无法获取组名吗? var venus = svg .append("g") .attr("id", "venus") .append("ellipse")...。这不会返回组的 ID venus
    • 你的意思是在dragend(d) {函数中?你可以在那里使用d3.select(this);d3.event
    猜你喜欢
    • 2018-11-02
    • 2022-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2021-07-22
    • 2011-07-05
    • 2016-03-05
    相关资源
    最近更新 更多