Canvas How to - Draw text inside a circle








Question

We would like to know how to draw text inside a circle.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<!-- ww  w .  j ava 2  s  .  c o m-->
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
        var canvas1 = document.getElementById("canvas");
        var context = canvas1.getContext("2d");
        context.beginPath();
        context.fillStyle = "yellow";
        context.strokeStyle = "black";
        context.font = "20px Georgia";
        context.lineWidth = 10;
        context.arc(100, 100, 75, 0, 2 * Math.PI, false);
        context.fill();
        context.beginPath();
        context.fillStyle = "red";
        context.fillText("Hello World!", 40, 100);
        context.fill();
});//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

The code above is rendered as follows: