利用canvas进行一个饼形图的绘制

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>绘制饼形图。</title>
    <style>
        canvas{
            border: 1px solid green;
        }
    </style>
</head>
<body>
    <!-- 绘制饼形图 -->
    <canvas width="500" height="500" id="canvas"></canvas>
</body>
<script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    function toAngle(radian){
        return radian*180/Math.PI;
    }
    function toRadian(angle){
        return angle*Math.PI/180;
    }
    /*将饼状图画出来*/
    var colors = 'green,yellow,pink,blue,red,lightgreen,lightblue'.split(',');
    var text = 'HTML5,Canvas,Javascript,Css3,Ajax,框架封装,jQuery与移动Web'.split(',');
    var x0 = canvas.width/2,
        y0 = canvas.height/2,
        radius = 100,
        start = -5,
        distance = 20,
        padding = 5,
        step = 360/colors.length;
    for(var i = 0 ; i < colors.length ; i   ){
        ctx.beginPath();
        ctx.fillStyle = colors[i];
        ctx.moveTo(x0,y0);
        ctx.arc(x0,y0,radius,toRadian(start),toRadian(start =step));
        ctx.fill();
        /*画斜线*/
        ctx.beginPath();
        ctx.strokeStyle = colors[i];
        var x1 = x0   (radius distance)*Math.cos(toRadian(( start-step/2 ))),
            y1 = y0   (radius distance)*Math.sin(toRadian(( start-step/2 )));
        ctx.moveTo(x0,y0);
        ctx.lineTo(x1,y1);
        ctx.stroke();
        /*写文字*/
        ctx.beginPath();
        ctx.fillStyle = colors[i];
        var textX = x1,
            textY = y1;
        if(start-step/2 > 90 && start-step/2 < 270){
            ctx.textAlign = 'right';
            textX = textX - padding;
        }else{
            ctx.textAlign = 'left';
            textX = textX   padding;
        }
        ctx.fillText(text[i],textX,textY-padding/2);
        /*画直线*/
        ctx.beginPath();
        ctx.moveTo(x1,y1);
        //计算文字的宽度
        var length = ctx.measureText( text[ i ] ).width
        if(start-step/2 > 90 && start-step/2 < 270){
            x1  = -2*padding-length;
        }else{
            x1  = 2*padding   length;
        }
        ctx.lineTo(x1,y1);
        ctx.stroke();
        /*画饼形图*/
        /*ctx.beginPath();
        ctx.fillStyle = colors[i];
        ctx.moveTo(x0,y0);
        ctx.arc(x0,y0,radius,toRadian(start),toRadian(start =step));
        ctx.fill();*/
    }
</script>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值