JSFiddle - React, Tailwind, and code Playground
HTML
<canvas width=400 height=400></canvas>
<button>Camembert</button>
CSS
canvas { outline: dashed thin gray; }
JavaScript
function randomColor( ){
return Array.reduce("xxx", function( accu, char ){
var hex = (Math.random() * 256 | 0).toString(16);
return accu + ["00", "0", ""][hex.length] + hex;
}, "#");
}
var $canvas = document.querySelector("canvas");
var cx = $canvas.getContext("2d");
function camembert( ){
// generates data
var figures = [];
for (var i = 3 + Math.random() * 9 | 0; i--;) {
figures.push(5 + Math.random() * 95 | 0);
}
var total = figures.reduce(function( a, b ){
return a + b;
});
console.info(figures);
console.info("nombre de parts", figures.length);
console.info("total", total);
// retrieves drawing parameters
var width = $canvas.width;
var height = $canvas.height;
var center = { x: width / 2, y: height / 2 };
var radius = Math.min(width, height) * 0.309;
// configures the drawing context
cx.clearRect(0, 0, width, height);
cx.save();
cx.translate(center.x, center.y);
cx.font = "bold 12px Verdana";
cx.lineWidth = 1.5;
cx.lineJoin = "bevel";
cx.strokeStyle = "rgba(0, 0, 0, 0.5)";
cx.shadowColor = "black";
// draws the disc's shadow
cx.shadowOffsetX = 1;
cx.shadowOffsetY = 1;
cx.shadowBlur = 2;
cx.beginPath();
cx.arc(0, 0, radius, 0, 2*Math.PI);
cx.fill();
cx.shadowBlur = 0;
cx.shadowOffsetX = 0;
cx.shadowOffsetY = 0;
var startAngle = -Math.PI / 2;
var delay = 0;
figures.forEach(function( figure ){
var stopAngle = startAngle + 2*Math.PI * figure/total;
// draws the quarter
cx.fillStyle = randomColor();
cx.beginPath();
cx.moveTo(0, 0);
cx.lineTo(radius * Math.cos(startAngle), radius * Math.sin(startAngle));
cx.arc(0, 0, radius, startAngle, stopAngle);
cx.closePath();
cx.fill();
cx.stroke();
// draws the text with a shadow
cx.shadowOffsetX = 1;
...