<!DOCTYPE html>
<html>
<head>
<title> Pie Charts</title>
</head>
<body>
<canvas id="pieChartCanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("pieChartCanvas");
var ctx = canvas.getContext("2d");
const circlePoints = []
function drawLine(ctx, pointStart, pointEnd) {
ctx.beginPath();
ctx.moveTo(pointStart.x, pointStart.y);
ctx.lineTo(pointEnd.x, pointEnd.y);
ctx.stroke();
}
var data1 = [
{ label: "Slice 1", value: 20, color: "#FF5733" },
{ label: "Slice 2", value: 80, color: "#FFC300" }
];
var data2 = [
{ label: "Slice 1", value: 10, color: "#36A2EB" },
{ label: "Slice 2", value: 90, color: "#8E44AD" }
];
function drawPieChart(data, centerX, centerY, radius, rotation) {
var total = data.reduce((sum, slice) => sum + slice.value, 0);
var minSlice = data.reduce(function (prev, current) {
return (prev.value < current.value) ? prev : current;
});
var minSliceAngle = (minSlice.value / 100) * Math.PI * 2;
var startAngle = rotation - minSliceAngle / 2;
for (var i = 0; i < data.length; i++) {
var sliceAngle = (data[i].value / total) * 2 * Math.PI;
// Calculate intersection point with the circle at the segment boundary
var angle = startAngle + sliceAngle;
var x = centerX + radius * Math.cos(angle);
var y = centerY + radius * Math.sin(angle);
circlePoints.push({ x: x, y: y })
// Draw the slice
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, startAngle + sliceAngle);
ctx.closePath();
ctx.fillStyle = data[i].color;
ctx.fill();
// Draw a point at the segment boundary
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.fillStyle = "#000";
ctx.fill();
// Update the starting angle for the next slice
startAngle += sliceAngle;
}
}
// Draw the two pie charts
// drawPieChart(data1, canvas.width / 4, canvas.height / 2, 100, -Math.PI / 4);
// drawPieChart(data2, canvas.width * 3 / 4, canvas.height / 2, 100, -Math.PI / 4 - Math.PI / 2);
drawPieChart(data1, canvas.width / 4, canvas.height / 2, 50, 0);
drawPieChart(data2, canvas.width * 3 / 4, canvas.height / 2, 50, 0);
//
drawLine(ctx, circlePoints[0], circlePoints[2],)
drawLine(ctx, circlePoints[1], circlePoints[3],)
</script>
</body>
</html>
canvas 饼图切线
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- canvas需要绑定鼠标事件,同时需要得到鼠标在 canvas 上面的位置和判断鼠标是否在饼图上面 绑定鼠标事件 ...