2016-08-22 45 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',将其值传递给函数更新)。 –