JSFiddle - React, Tailwind, and code Playground
by sutherland
HTML
<canvas id="graph1" width="400" height="400"></canvas>
CSS
canvas {
margin: 10px;
width: 400px;
}
JavaScript
// Args
// elementId: string containing canvas element's ID
// slices: array containing slice names, colors, and values
function simpleChart(elementId, slices, animated, offset, scale) {
// Initialize key variables
this.element = document.getElementById(elementId);
this.slices = slices;
this.animated = animated;
this.offset = (typeof(offset) === 'undefined') ? 0 : offset;
this.scale = (typeof(scale) === 'undefined') ? 1 : scale;
// Canvas context
this.context = this.element.getContext('2d');
// Interval
var interval;
var time = 0;
// Determine size
var width = this.element.getAttribute('width');
var height = this.element.getAttribute('height');
this.size = (width < height) ? width : height;
// Retina compatibility
if (window.devicePixelRatio == 2) {
this.element.setAttribute('width', this.size * 2);
this.element.setAttribute('height', this.size * 2);
this.context.scale(2, 2);
}
// Create graph using the slices
this.createGraph = function() {
if (this.animated) {
interval = setInterval(function() {
this.animate();
}, 10);
} else {
this.drawGraph();
}
}
this.animate = function() {
time++;
this.scale = time * 0.01;
if (this.scale == 1) clearInterval(interval);
this.drawGraph();
}
// Draws the graphic
this.drawGraph = function() {
this.context.clearRect(0, 0, size, size);
var previous = 0 + this.offset;
for (var i = 0; i < this.slices.length; i++) {
currentVal = this.slices[i].value * this.scale;
this.drawSlice(previous, currentVal + previous, false, this.slices[i].color);
previous = currentVal + previous;
}
}
// Creates a slice
this.drawSlice = function(start, stop, name, color) {
this.context.beginPath();
this.context.arc((this.size...