作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要你的帮助,我的问题是如果我想使用 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);
}
在此处查看实际效果:
关于javascript - 如何使用 Canvas 绘制圆环图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23651987/
我是一名优秀的程序员,十分优秀!