2016-08-22 43 views
3

我想調用更新函數來旋轉文本1度,一旦度數達到360再次旋轉角度變爲0,因此它將繼續旋轉。但我認爲這不是解決這個問題的正確方法,也是行不通的。因此,如果有人知道這一點,建議我這樣做。 如何在D3 js中連續旋轉任何形狀?

<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script> 
</head> 
<body> 
<script> 
var width = 600; 
var height = 300; 

var holder = d3.select("body") 
    .append("svg") 
    .attr("width", width)  
    .attr("height", height); 

// draw the text 
holder.append("text") 
.style("fill", "black") 
.style("font-size", "56px") 
.attr("dy", ".35em") 
.attr("text-anchor", "middle") 
.attr("transform", "translate(300,150) rotate(0)") 
.text("Hi, how r u doing"); 

// Initial starting angle of the text 

for(var i=0;i<=360;i++){ 
    update(i); 
    if(i==360){i=0;} 
} 


var n; 
// update the element 
function update(n) { 
// rotate the text 
holder.select("text") 
.transition() 
.duration(2000) 
.attr("transform", "translate(300,150) rotate("+n+")"); 
} 


</script> 

</body> 
</html> 

例JS小提琴here

+0

你可以發佈一個jsFiddle嗎? –

+0

你知道for循環每秒執行數十萬次,不是嗎? –

+0

是的,我知道,這就是爲什麼我正在尋找其他方法來做到這一點。如果你知道的話請告訴我。 @GerardoFurtado –

回答

3

您的for循環永遠不會結束,因爲您在計數完成前將計數器i重置爲0。如果你刪除這一行,代碼將不會有可見的結果,因爲for循環執行得這麼快,在你看到任何東西之前它已經完成。

更好的解決方案是使用setInterval例如

var width = 600; 
var height = 300; 

var holder = d3.select("body") 
    .append("svg") 
    .attr("width", width)  
    .attr("height", height); 

// draw the text 
holder.append("text") 
.style("fill", "black") 
.style("font-size", "56px") 
.attr("dy", ".35em") 
.attr("text-anchor", "middle") 
.attr("transform", "translate(300,150) rotate(0)") 
.text("Hi, how r u doing"); 

// Initial starting angle of the text 

var i = 0; 
var timeInterval = 10; 
setInterval(function(){ 
     i += 1; 
     update(i % 360) 
    },timeInterval); 


var n; 
// update the element 
function update(n) { 
// rotate the text 
holder.select("text") 
.attr("transform", "translate(300,150) rotate("+n+")"); 
} 

您可以通過調整timeInterval變量來控制速度。

我已經添加了一個例子JS小提琴here

+0

Upvoted,但你爲什麼使用模('i℅360')?單獨使用'i'就可以工作:360,720,1080等都是相同的角度。 –

+0

@GerardoFurtado這裏只是一個猜測 - 避免溢出櫃檯? –

+0

計數器不會停止增加(計數器是'i',將其值傳遞給函數更新)。 –