Canvas How to - Rotate text along circle








Question

We would like to know how to rotate text along circle.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.0.2.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){<!--from   w  w w .jav  a  2  s.  c  o m-->
CanvasRenderingContext2D.prototype.fillTextCircle = function(text,x,y,radius,startRotation){
   var numRadsPerLetter = 2*Math.PI / text.length;
   this.save();
   this.translate(x,y);
   this.rotate(Math.PI*2/100*step++);
   this.rotate(startRotation);
   for(var i=0;i<text.length;i++){
      this.save();
      this.rotate(i*numRadsPerLetter);
      this.fillText(text[i],0,-radius);
      this.restore();
   }
   this.restore();
}
var ctx = $('canvas').get(0).getContext('2d');
var step = 0;
setInterval(function() {
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.save();
    ctx.fillTextCircle('java2s.com', 100, 100, 80, 0);
    ctx.restore();
}, 1000);
});//]]>  
</script>
</head>
<body>
  <canvas height="1000" width="1000" />
</body>
</html>

The code above is rendered as follows: