使用 JavaScript 我正在尝试编写一个饼图来部分填充 颜色占切片面积百分比的切片从 圆的中心。下面的代码运行正常,但填充 整个切片的颜色,我只想填充百分比 使用 ariFillPercent 的 iNdx。
如果有一个例子展示如何做到这一点那就太好了。
const ariSizes = [120, 100, 140];
const arsColors = ["#FFDAB9", "#E6E6FA", "#E0FFFF"];
const ariFillPercent = [22, 32, 55];
//==== FUNCTION ====//
const handleDrawSegment = (cnv, ctx, iNdx) => {
ctx.save();
var centerX = Math.floor(cnv.width / 2);
var centerY = Math.floor(cnv.height / 2);
let radius = Math.floor(cnv.width / 2);
var startingAngle = handleDegreesToRadians(handleSumTo(ariSizes, iNdx));
var arcSize = handleDegreesToRadians(ariSizes[iNdx]);
var endingAngle = startingAngle + arcSize;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius,
startingAngle, endingAngle, false);
ctx.closePath();
ctx.fillStyle = arsColors[iNdx];
ctx.fill();
ctx.restore();
}
试试这个
const ariSizes = [120, 100, 140];
const arsColors = ["#FFDAB9", "#E6E6FA", "#E0FFFF"];
const ariFillPercent = [22, 32, 55];
const handleDegreesToRadians = (degrees) => (degrees * Math.PI) / 180;
//==== FUNCTION ====//
const handleDrawSegment = (cnv, ctx, iNdx) => {
ctx.save();
var centerX = Math.floor(cnv.width / 2);
var centerY = Math.floor(cnv.height / 2);
let radius = Math.floor(cnv.width / 2);
var startingAngle = handleDegreesToRadians(handleSumTo(ariSizes, iNdx));
var arcSize = handleDegreesToRadians(ariSizes[iNdx]);
var endingAngle = startingAngle + arcSize;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
const fillAngle = handleDegreesToRadians((ariFillPercent[iNdx] / 100) * ariSizes[iNdx]);
ctx.arc(centerX, centerY, radius, startingAngle, startingAngle + fillAngle, false);
ctx.lineTo(centerX, centerY);
ctx.closePath();
ctx.fillStyle = arsColors[iNdx];
ctx.fill();
ctx.restore();
};
const handleSumTo = (arr, index) => {
let sum = 0;
for (let i = 0; i < index; i++) {
sum += arr[i];
}
return sum;
};
// Example usage:
const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");
// Call handleDrawSegment for each slice
for (let i = 0; i < ariSizes.length; i++) {
handleDrawSegment(canvas, context, i);
}