Skip to content

Instantly share code, notes, and snippets.

@abranhe
Last active September 16, 2024 22:08
Show Gist options
  • Save abranhe/99f450e50d05943adf7f0ea84f2e3972 to your computer and use it in GitHub Desktop.
Save abranhe/99f450e50d05943adf7f0ea84f2e3972 to your computer and use it in GitHub Desktop.
// src/components/Gauge.js
import React from 'react';
const Gauge = ({ value = 50, max = 100, size = 100 }) => {
const radius = size / 2 - 10;
const circumference = 2 * Math.PI * radius;
const offset = circumference - (value / max) * circumference;
return (
<div className="flex justify-center items-center">
<svg width={size} height={size} className="transform rotate-[-90deg]">
<circle
cx={size / 2}
cy={size / 2}
r={radius}
stroke="#e5e7eb" // Tailwind's gray-200
strokeWidth="10"
fill="transparent"
/>
<circle
cx={size / 2}
cy={size / 2}
r={radius}
stroke="#3b82f6" // Tailwind's blue-500
strokeWidth="10"
fill="transparent"
strokeDasharray={circumference}
strokeDashoffset={offset}
strokeLinecap="round"
/>
</svg>
<div className="absolute text-center text-2xl font-bold text-gray-700">
{value}%
</div>
</div>
);
};
export default Gauge;
// src/components/HalfGauge.js
import React from 'react';
const HalfGauge = ({ value = 50, max = 100, size = 200 }) => {
const radius = size / 2 - 10;
const circumference = Math.PI * radius; // For half-circle
const offset = circumference - (value / max) * circumference;
return (
<div className="relative">
<svg width={size} height={size / 2} className="overflow-visible">
{/* Background semi-circle */}
<path
d={describeArc(size / 2, size / 2, radius, 0, 180)}
stroke="#e5e7eb" // Tailwind's gray-200
strokeWidth="10"
fill="transparent"
/>
{/* Progress semi-circle */}
<path
d={describeArc(size / 2, size / 2, radius, 0, 180)}
stroke="#3b82f6" // Tailwind's blue-500
strokeWidth="10"
fill="transparent"
strokeDasharray={circumference}
strokeDashoffset={offset}
strokeLinecap="round"
/>
</svg>
{/* Value Display */}
<div className="absolute inset-0 flex justify-center items-center top-[15%] text-2xl font-bold text-gray-700">
{value}%
</div>
</div>
);
};
// Helper function to describe the arc for a semi-circle
function describeArc(x, y, radius, startAngle, endAngle) {
const start = polarToCartesian(x, y, radius, endAngle);
const end = polarToCartesian(x, y, radius, startAngle);
const largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";
const d = [
"M", start.x, start.y,
"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
].join(" ");
return d;
}
// Convert degrees to cartesian coordinates
function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
const angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
}
export default HalfGauge;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment