Create a Multi-Color Chart in HTML with Canvas
Here is an example of a multi-color chart in HTML using the <canvas> element and JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Multi-Color Chart</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id='myCanvas' width='500' height='300'></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Define data for chart
const data = [
{ label: 'A', value: 20, color: 'red' },
{ label: 'B', value: 30, color: 'orange' },
{ label: 'C', value: 50, color: 'yellow' },
{ label: 'D', value: 40, color: 'green' },
{ label: 'E', value: 10, color: 'blue' },
];
// Calculate total value
const total = data.reduce((acc, curr) => acc + curr.value, 0);
// Draw chart
let startAngle = 0;
data.forEach((item) => {
const endAngle = (item.value / total) * 2 * Math.PI + startAngle;
ctx.beginPath();
ctx.fillStyle = item.color;
ctx.moveTo(canvas.width / 2, canvas.height / 2);
ctx.arc(
canvas.width / 2,
canvas.height / 2,
Math.min(canvas.width, canvas.height) * 0.4,
startAngle,
endAngle
);
ctx.lineTo(canvas.width / 2, canvas.height / 2);
ctx.fill();
startAngle = endAngle;
});
</script>
</body>
</html>
This code creates a canvas element with a width of 500 pixels and a height of 300 pixels. It then defines an array of data for the chart, where each item has a label, value, and color. The total value is calculated by adding up all the values in the data array.
The chart is drawn using the ctx.arc() method, which draws a circular arc. The start and end angles are calculated based on the value of each item and the total value. The ctx.fill() method is used to fill the arc with the color specified in the data array.
The result is a multi-color chart with each segment representing a different item in the data array. The colors are defined by the color property of each item, and the labels are not included in this example but could be added using additional HTML and CSS.
原文地址: https://www.cveoy.top/t/topic/ozmQ 著作权归作者所有。请勿转载和采集!