JSFiddle - React, Tailwind, and code Playground
by alr3
HTML
<canvas id="canvas" width="500" height="500"></canvas>
JavaScript
function fromDegreeToAngle(degrees) {
return degrees * Math.PI / 180;
}
function drawArc(options) {
var context = options.canvas.getContext('2d');
var valuesSummed = 0;
for(curIdx in options.values) valuesSummed += options.values[curIdx].value;
var seperationDegrees = 2;
var startDegrees = options.startingDegree + 180; //The canvas arc starts on the far right side of the circle...I think starting on the far left is best, so auto correctiong for this
var howLongIsThisArcInPercentage = options.values[options.curValueIdx].value / valuesSummed;
var howLongIsThisArcInDegrees = howLongIsThisArcInPercentage * 360;
var endDegrees = howLongIsThisArcInDegrees + startDegrees - seperationDegrees;
var counterClockwise = false;
context.beginPath();
console.log(startDegrees + ' :::: ' + endDegrees + '______' + seperationDegrees);
context.arc(options.x, options.y, options.radius,
fromDegreeToAngle(startDegrees),
fromDegreeToAngle(endDegrees),
counterClockwise);
context.lineWidth = 8;
// line color
context.strokeStyle = '#B3B3B4';
context.stroke();
var startDegreesInner = startDegrees + 3;
var endDegreesInner = endDegrees - 3;
var contextInner = options.canvas.getContext('2d');
contextInner.beginPath();
contextInner.arc(options.x, options.y, options.radius,
fromDegreeToAngle(startDegreesInner),
fromDegreeToAngle(endDegreesInner),
counterClockwise);
contextInner.lineWidth = 3;
// line color
contextInner.strokeStyle = options.values[options.curValueIdx].color;
contextInner.stroke();
return endDegrees - 180 + seperationDegrees;//What are the actual degrees we are ending on...unconvert that 180 we added earlier
}
function drawAllArcs(canvasId, values) {
var previousStartingDegree = 0;
var canvas = document.getElementById(canvasId);
for(curIdx in values) {
previousStartingDegree = drawArc({
x: (canvas.width / 2),
y: (canvas.height / 2),
radius:...