html5 canvas chart,javascript - HTML5 Canvas pie chart - Stack Overflow

本文作者改进了代码组织,通过数据对象数组和明确的属性声明,使代码更易理解。展示了如何利用数据对象管理标签、百分比和颜色,便于图表绘制和输入框关联。CodePen实例展示了实践效果:https://codepen.io/zfrisch/pen/pRbZebv.

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I like the previous answer, but I felt it was lacking in code clarity and it didn't really cover how to utilize labels.

I moved the values into a data object array for easy declaration. Other values, like percentage, I explicitly declared as a property on the data object, or as a separate variable. This, I think, makes it easier to read.

The refactoring also made it easier to tie the values to input boxes if that's something you're interested in.

To see what I mean and play with the values check out this CodePen: http://codepen.io/zfrisch/pen/pRbZeb

var data = [{

label: "one",

value: 100,

color: 'white'

}, {

label: "two",

value: 100,

color: 'skyBlue'

}, {

label: "three",

value: 100,

color: 'yellow'

}];

var total = 0;

for (obj of data) {

total += obj.value;

}

var canvas = document.getElementById('myCanvas');

var ctx = canvas.getContext('2d');

var previousRadian;

var middle = {

x: canvas.width / 2,

y: canvas.height / 2,

radius: canvas.height / 2,

};

//background

ctx.beginPath();

ctx.arc(middle.x, middle.y, middle.radius, 0, 2 * Math.PI);

ctx.closePath();

ctx.stroke();

ctx.fillStyle = "black";

ctx.fill();

//end of background

for (obj of data) {

previousRadian = previousRadian || 0;

obj.percentage = parseInt((obj.value / total) * 100)

ctx.beginPath();

ctx.fillStyle = obj.color;

obj.radian = (Math.PI * 2) * (obj.value / total);

ctx.moveTo(middle.x, middle.y);

//middle.radius - 2 is to add border between the background and the pie chart

ctx.arc(middle.x, middle.y, middle.radius - 2, previousRadian, previousRadian + obj.radian, false);

ctx.closePath();

ctx.fill();

ctx.save();

ctx.translate(middle.x, middle.y);

ctx.fillStyle = "black";

ctx.font = middle.radius / 10 + "px Arial";

ctx.rotate(previousRadian + obj.radian);

var labelText = "'" + obj.label + "' " + obj.percentage + "%";

ctx.fillText(labelText, ctx.measureText(labelText).width / 2, 0);

ctx.restore();

previousRadian += obj.radian;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值