JSFiddle - React, Tailwind, and code Playground
JavaScript
var img = document.getElementById('guage');
var percentDisplay = 73;
makeAnimatedGuage(img, percentDisplay);
function makeAnimatedGuage(img, percentDisplay, line_width = 10, guage_width = 500, font_size = 20, font_face = 'Arial'){
var current_pct = 0;
var target_pct = 65;
img.src = makeGuage(current_pct);
animateGuage();
function animateGuage(){
requestAnimationFrame(()=>{
current_pct++;
img.src = makeGuage(current_pct);
if(current_pct !== target_pct){
animateGuage();
}
});
}
function makeGuage(percentDisplay, line_width = 10, guage_width = 500, font_size = 20, font_face = 'Arial') {
const pctToDegrees = pct => (180 / 100 * pct) + 180;
function getRadialPosition(center, radius, angle) {
return {
x: (center.x + radius * Math.cos(angle * (Math.PI / 180))),
y: (center.y + radius * Math.sin(angle * (Math.PI / 180)))
};
}
var canvas = document.createElement("canvas");
canvas.width = guage_width;
canvas.height = (guage_width / 2) + (line_width / 2);
var ctx = canvas.getContext("2d");
ctx.lineCap = 'round';
ctx.lineWidth = line_width;
ctx.font = `${font_size}px ${font_face}`;
var gradient = ctx.createLinearGradient(100, 0, canvas.width - 100, 0);
gradient.addColorStop(0, '#e23131');
gradient.addColorStop(.85, '#fbe500');
gradient.addColorStop(1, '#25cd6b');
ctx.strokeStyle = gradient;
var x = canvas.width / 2;
var y = canvas.height - (line_width / 2);
var radius = (canvas.width / 2) - (line_width / 2);
ctx.arc(x, y, radius, 0, Math.PI, true);
ctx.stroke();
var markers = [{
pct: 0,
baseline: 'bottom',
textAlign: 'left'
}, {
pct: 25,
baseline: 'top',
textAlign: 'left'
}, {
pct: 50,
baseline: 'top',
textAlign: 'center'
}, {
pct: 75,
baseline: 'top',
textAlign: 'right'
}, {
pct: 100,
baseline: 'bottom',
textAlign: 'right'
}];
markers.forEach(marker => {
var deg = pctToDegrees(marker.pct);
var start =...