繁体   English   中英

在每个点击事件上向前移动一个圆圈 100 像素

[英]Move a circle 100px forward on every click event

我正在学习 D3.js。 我编写了以下代码,在点击时移动圆圈。 我想在每次点击时将这个圆圈从当前的 position 向前移动(+100px)。

我想在没有 CSS 的情况下做到这一点

以下是我的代码

var svgContainer = d3.select("body").append("svg").attr("id", "root")
  .attr("width", 500)
  .attr("height", 500).append("g")


//Draw the Circle
var circle = svgContainer.append("circle")
  .attr("id", "Zubi")
  .attr("cx", 100)
  .attr("cy", 30)
  .attr("r", 20)
  .on("click", function() {
    d3.select(this)
      .transition()
      .duration(3000)
      .style("fill", "red")
      .attr("cx", 100)
  })
//.attr("transform", "translate(200,200)")})

实现您想要的最简单的方法是使用 getter ( selection.attr("cx") ) 来获取当前的 position 并增加它。 您也可以使用translate ,但由于您是 D3 学习者,因此使用 circle 的cx属性可能更容易理解。

下面是一个demo,每次点击增加50px:

 const circle = d3.select("circle").on("click", function() { d3.select(this).transition().attr("cx", +d3.select(this).attr("cx") + 50) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg width="500" height="100"> <circle cx="50" cy="50" r="30" fill="teal"></circle> </svg>

请记住,getter 总是返回一个string ,所以你必须将它强制转换为一个数字。

此外,由于您在选择中只有一个元素并且它有一个名称,因此您不需要d3.select(this)

 const circle = d3.select("circle").on("click", function() { circle.transition().attr("cx", +circle.attr("cx") + 50) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg width="500" height="100"> <circle cx="50" cy="50" r="30" fill="teal"></circle> </svg>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM