Gloom
Gloom

Reputation: 39

Radial chart using js and html5 canvas element

I'm trying to make circular chart on html5 canvas el.

(function () {
        var ctx = document.getElementById('canvas').getContext('2d');
        var counter = 0;
        var start = 4.72;
        var cW = ctx.canvas.width;
        var cH = ctx.canvas.height;
        var diff;
        var maxVal = 44;

        function progressChart(){
            diff = ((counter / 100) * Math.PI*2*10).toFixed(2);
            ctx.clearRect(0, 0, cW, cH);
            ctx.lineWidth = 15;
            ctx.fillStyle = '#ff883c';
            ctx.strokeStyle = '#ff883c';
            ctx.textAlign = 'center';
            ctx.font = '25px Arial';
            ctx.fillText(counter+'%', cW*.5, cH*.55, cW);
            ctx.beginPath();
            ctx.arc(70, 70, 60, start, diff/10+start, false);
            ctx.stroke();
            if(counter >= maxVal){
                clearTimeout(drawChart);
            }
            counter++;
        }
        var drawChart = setInterval(progressChart, 20);
    })();
<canvas id="canvas" width="140" height="140"></canvas>

I want to add doughnut background before browser start drawing fill chart. Unfortunately, I need to use ctx.clearRect() because I've got strange visual effect. Is any way to combine this two rings?

Upvotes: 0

Views: 319

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

Yes, there is a way and that is, drawing another arc for doughnut background, before drawing fill chart.

Also, you should use requestAnimationFrame() instead of setInterval(), for better efficiency.

var ctx = document.getElementById('canvas').getContext('2d');
var counter = 0;
var start = 4.72;
var cW = ctx.canvas.width;
var cH = ctx.canvas.height;
var diff;
var maxVal = 44;
var rAF;

function progressChart() {
   diff = ((counter / 100) * Math.PI * 2 * 10).toFixed(2);
   ctx.clearRect(0, 0, cW, cH);
   ctx.lineWidth = 15;
   ctx.fillStyle = '#ff883c';
   ctx.textAlign = 'center';
   ctx.font = '25px Arial';
   ctx.fillText(counter + '%', cW * .5, cH * .55, cW);

   // doughnut background
   ctx.beginPath();
   ctx.arc(70, 70, 60, 0, Math.PI * 2, false);
   ctx.strokeStyle = '#ddd';
   ctx.stroke();

   // fill chart
   ctx.beginPath();
   ctx.arc(70, 70, 60, start, diff / 10 + start, false);
   ctx.strokeStyle = '#ff883c';
   ctx.stroke();

   if (counter >= maxVal) {
      cancelAnimationFrame(rAF);
      return;
   }
   counter++;
   rAF = requestAnimationFrame(progressChart);
}

progressChart();
<canvas id="canvas" width="140" height="140"></canvas>

Upvotes: 3

Related Questions