rohit ujjwal rohit ujjwal - 3 months ago 13
Javascript Question

how to rotate any shape continuously in D3 js?

I am trying to call the update function to rotate the text by 1 degree and once the degree reaches 360 again the rotation angle becomes 0 and hence it will keep on rotating. But I think this is not the right way to approach the problem also it is not working. So suggest me the way to do it if anyone know it.



<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>


Example JS Fiddle here.

Answer

Your for loop never ends as you reset the counter i to 0 just before it finishes. If you remove this line, the code will have no visible result as the for loop executes so quickly, it's already completed before you can see anything.

A better solution is to use setInterval e.g.

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

You can control the speed by adjusting the timeInterval variable.

I've added an example JS Fiddle here.