JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<button id="again">Again</button>
<br>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
}
#canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// set context styles
ctx.lineWidth = 15;
ctx.strokeStyle = '#85c3b8';
ctx.shadowColor = "black"
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 0;
ctx.font = "18px verdana";
var quart = Math.PI / 2;
var PI2 = Math.PI * 2;
var percent = 0;
var guages = [];
guages.push({
x: 50,
y: 100,
radius: 40,
start: 0,
end: 70,
color: "blue"
});
guages.push({
x: 200,
y: 100,
radius: 40,
start: 0,
end: 90,
color: "green"
});
guages.push({
x: 50,
y: 225,
radius: 40,
start: 0,
end: 35,
color: "gold"
});
guages.push({
x: 200,
y: 225,
radius: 40,
start: 0,
end: 55,
color: "purple"
});
animate();
function drawAll(percent) {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw all the guages
for (var i = 0; i < guages.length; i++) {
render(guages[i], percent);
}
}
function render(guage, percent) {
var pct = percent / 100;
var extent = parseInt((guage.end - guage.start) * pct);
var current = (guage.end - guage.start) / 100 * PI2 * pct - quart;
ctx.beginPath();
ctx.arc(guage.x, guage.y, guage.radius, -quart, current);
ctx.strokeStyle = guage.color;
ctx.stroke();
ctx.fillStyle = guage.color;
ctx.fillText(extent, guage.x - 15, guage.y + 5);
}
function animate() {
// if the animation is not 100% then request another frame
if (percent < 100) {
requestAnimationFrame(animate);
}
// redraw all guages with the current percent
drawAll(percent);
// increase percent for the next frame
percent += 1;
}
$("#again").click(function () {
percent = 0;
animate();
});