美文网首页
10饼状图

10饼状图

作者: 夜幕小草 | 来源:发表于2016-12-07 23:16 被阅读24次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas绘制饼状图</title>
</head>
<body style="padding: 100px;">
  <canvas id="canvas" width="900" height="600" style="border:1px solid #000"></canvas>

<script>
     // 1. 获取标签
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    // 2. 数据
    var data = [
        {name: '上海', color: 'red', value: .1},
        {name: '北京', color: 'green', value: .3},
        {name: '广州', color: 'blue', value: .15},
        {name: '深圳', color: 'orange', value: .25},
        {name: '杭州', color: 'pink', value: .2}
    ];

    // 3. 绘制
    // 3.1 常量
    var x0 = canvas.width * 0.5,
        y0 = canvas.height * 0.5;
    var radius = 150;
    var beginAngle = -90 * Math.PI / 180;

    for(var i=0; i<data.length; i++){
        // 结束角度
        var tempAngle = 360 * data[i].value * Math.PI / 180,
            endAngle = beginAngle + tempAngle;

        ctx.beginPath();
        // 设置起点
        ctx.moveTo(x0, y0);
        ctx.arc(x0, y0, radius, beginAngle, endAngle);
        ctx.fillStyle = data[i].color;
        ctx.fill();

        // 更新起始角度
        beginAngle = endAngle;
    }

</script>
</body>
</html>

相关文章

网友评论

      本文标题:10饼状图

      本文链接:https://www.haomeiwen.com/subject/vwlhmttx.html