How to Create a Circular Shape Progress Bar Using HTML5 Canvas ~ Hybrid Mobile Apps Development, React Native, Flutter, JavaScript, Darts, iOS, Android, NodeJS
Coding Savvy FB Twitter Google
» »

How to Create a Circular Shape Progress Bar Using HTML5 Canvas

Displaying the progress of an ongoing operation to the users is one of the best way of representing a process progress in web applications. Now here is how to spice it up a bit, Making the progress bar in circular shape is now the most used style for a process that might take long. This is also very useful when you want to use a progress bar to represent any form of rating in percentage in your own applications. It make it look more presentable than the basic old lame rectangular progress bar.
How to Create a Circular Shape Progress Bar Using HTML5 Canvas

Download Script Live Demo

Let first create our canvas using HTML5 canvas element tag.
<div class="chart" id="graph" data-percent="2"></div>

Now let use JavaScript to draw on our new canvas, The Bar progress will be triggered by a button.

var el = document.getElementById('graph'); // get canvas
var inc = document.getElementById("inc");
var options = {
percent: el.getAttribute('data-percent') || 25,
size: el.getAttribute('data-size') || 220,
lineWidth: el.getAttribute('data-line') || 15,
rotate: el.getAttribute('data-rotate') || 0
}
var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;
el.appendChild(span);
el.appendChild(canvas);
ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg
//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;
var drawCircle = function(color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
ctx.lineCap = 'round'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#4ec120', options.lineWidth, options.percent / 100);
inc.onclick=function(){
setInterval(function(){
options.percent=parseInt(options.percent)+2;
if (!(options.percent > 100)) {
span.textContent = options.percent+ '%';
drawCircle('#4ec120', options.lineWidth, options.percent / 100);
}
}, 100);}

The end.
Was this article helpful?
Thanks! Your feedback helps us improve tutorials.

You May Also Like...

No comments:

Post a Comment