gpt4 book ai didi

javascript - 如何使用 Canvas 绘制圆环图?

转载 作者:行者123 更新时间:2023-11-30 08:02:56 25 4
gpt4 key购买 nike

我需要你的帮助,我的问题是如果我想使用 canvas 绘制圆环图,我该如何使用 canvas 和 java 脚本来完成,

我写了下面的代码但是不知道怎么完成

<body>

<canvas id="chart" width="500" height="500" style="background-color:black"> </canvas>

<script type="text/javascript">

var canvas = document.getElementById("chart");
var chart = canvas.getContext("2d");

function drawdountChart(canvas)
{

this.x , this.y , this.radius , this.lineWidth , this.strockStyle , this.from , this.to = null;
this.set = function( x, y, radius, from, to, lineWidth, strockStyle)
{
this.x = x;
this.y = y;
this.radius = radius;
this.from=from;
this.to= to;
this.lineWidth = lineWidth;
this.strockStyle = strockStyle;
}

this.draw = function(data)
{
canvas.beginPath();
canvas.lineWidth = this.lineWidth;
canvas.strokeStyle = this.strockStyle;
canvas.arc(this.x , this.y , this.radius , this.from , this.to);
canvas.stroke();
var numberOfParts = data.numberOfParts;
var parts = data.parts.pt;
var colors = data.colors.cs;
for(var i = 0; i<numberOfParts; i++)
{

}
}
}
var data =
{
numberOfParts: 4,
parts:{"pt": [20 , 30 , 25 , 25]},//percentage of each part
colors:{"cs": ["red", "green", "blue", "yellow" ]}//color of each part
};

var drawDount = new drawdountChart(chart);
drawDount.set(150, 150, 100, 0, Math.PI*2, 30, "#FFF");
drawDount.draw(data);



</script>


</body>

现在我必须将内容放入 for 循环中。

请大家帮帮我。

最佳答案

你会想要渲染这样的部分:

var df = 0; //keep track of how far round the donut we are.

for(var i = 0; i<numberOfParts; i++) {
canvas.beginPath();
canvas.strokeStyle = colors[i]; // get the color
// Calculate the % of a circle (2PI) to arc
canvas.arc(this.x, this.y, this.radius, df, df + (Math.PI * 2) * (parts[i] / 100));
canvas.stroke();
// Update our progress around the donut so we know where to draw the next part
df += (Math.PI * 2) * (parts[i] / 100);
}

在此处查看实际效果:

http://jsfiddle.net/RgLAU/1/

关于javascript - 如何使用 Canvas 绘制圆环图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23651987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com