Canvas How to - Draw percent chart








Question

We would like to know how to draw percent chart.

Answer


<!--   w  ww . ja v  a2  s . c o m-->



<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.js'></script>

<script type='text/javascript'>//<![CDATA[ 
$(function(){
window.onload = function() {
        canvas  = $('#timer'),
        percent = +canvas.data('completeness'),
        ctx     = canvas.get(0).getContext('2d'), 
    ctx.lineWidth = 9;
    ctx.strokeStyle = ctx.fillStyle = "#00EE00";
    var endAngle = (Math.PI * percent * 2 / 100);
    ctx.arc(50, 50, 35, -(Math.PI/180*90), endAngle - (Math.PI/180*90), false);   
    ctx.stroke(); 
    ctx.font = "bold 13px Arial"; 
    ctx.fillText(percent + "%", 40, 53);
}
});//]]>  
</script>
</head>
<body>
  <div>
    <canvas id="timer" width="100" height="100" data-completeness="75"></canvas>
  </div>
</body>
</html>

The code above is rendered as follows: