简体   繁体   English

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

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

I am learning D3.js.我正在学习 D3.js。 I wrote following code which moves the circle on click.我编写了以下代码,在点击时移动圆圈。 I want to move this circle forward (+100px) from its current position on every click.我想在每次点击时将这个圆圈从当前的 position 向前移动(+100px)。

I want to do it without CSS我想在没有 CSS 的情况下做到这一点

Following is my code以下是我的代码

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)")})

The easiest way to achieve what you want is using a getter ( selection.attr("cx") ) to get the current position and increasing it.实现您想要的最简单的方法是使用 getter ( selection.attr("cx") ) 来获取当前的 position 并增加它。 You can also use a translate , but since you're a D3 learner using the circle's cx attribute is probably easier to understand.您也可以使用translate ,但由于您是 D3 学习者,因此使用 circle 的cx属性可能更容易理解。

Here is a demo, each click increases 50px:下面是一个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>

Have in mind that the getter always returns a string , so you have to coerce it to a number.请记住,getter 总是返回一个string ,所以你必须将它强制转换为一个数字。

Also, since you have just one element in the selection and it has a name, you don't need d3.select(this) :此外,由于您在选择中只有一个元素并且它有一个名称,因此您不需要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