JSFiddle - React, Tailwind, and code Playground
by blineberry
HTML
<canvas id="canvas" height="500" width="500">Fallback Content</canvas>
JavaScript
var canvas = $("canvas");
var cxt=canvas[0].getContext("2d");
var centerX= canvas.width() / 2;
var centerY= canvas.height() / 2;
var pie = new PieChart({
centerX: centerX,
centerY: centerY
});
pie.drawPie(cxt);
function PieChart(args) {
this.centerX = args.centerX || 0;
this.centerY = args.centerY || 0;
this.radius = args.radius || getRadius(this.centerX,this.centerY);
this.startingAngle = args.startingAngle || 0;
this.direction = args.direction || false;
this.slices = {
values: args.sliceValues || [100,100],
total: 0
};
this.slices.total = getSliceTotal(this.slices.values);
this.color = args.color || "000";
this.drawPie = function(cxt) {
for (var i = 0; i < this.slices.values.length; i++) {
var endingAngle = (this.slices.values[i] / this.slices.total * Math.PI * 2) + this.startingAngle;
cxt.beginPath();
cxt.arc(this.centerX,
this.centerY,
this.radius,
this.startingAngle,
endingAngle,
this.direction);
cxt.lineTo(this.centerX,this.centerY);
cxt.closePath();
cxt.fill();
this.startingAngle = endingAngle;
}
};
this.addSlice = function(val) {
this.slices.values.push(val);
this.slices.total = getSliceTotal(this.slices.values);
return this.slices;
};
function getRadius(centerX,centerY) {
var radius;
if ((centerX - centerY) > 0) {
radius = centerX * .9;
return radius;
}
else {
radius = centerY * .9;
return radius;
}
}
function getSliceTotal(values) {
var total = 0;
for (var i = 0; i <values.length; i++) {
total += values[i];
...