[英]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.