canvas画虚线圆

本文要完成的图形
《canvas画虚线圆》

一个简朴的占比统计。。

完成的计划是html js合成

首先是简朴的HTML规划

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"> 
<title>statistics</title>
<script src="jquery.min.js"></script>
</head>
<body>
<style>
    .zh-chart {
        width: 100px;
        height: 100px;
        background: #142838;
    }
</style>
<div class="zh-chart" data-b="40/50" data-c="20/30" data-d="10/50" data-e="30/30" data-f="20/70"></div>
</body>
</html>

然后经由过程js来完成我们的终究结果,响应的操纵都有解释。

<script>
    var chartEle = $('.zh-chart');
    var canvas = document.createElement('canvas');
    canvas.width = chartEle.width();
    canvas.height = chartEle.height();
    var radius = canvas.width/2;
    chartEle.append(canvas);
    var ctx = canvas.getContext('2d');
    // 内圆
    ctx.arc(radius, radius, radius*2/3, 0, 2*Math.PI);
    ctx.fillStyle="rgba(22,196,203,0.1)";
    ctx.fill();
    ctx.strokeStyle = '#16C4CB';
    ctx.stroke();
    // 虚线圆环
    ctx.translate(radius, radius); // 转变扭转中间
    ctx.beginPath();
    ctx.arc(0, 0, radius*2/3+4, 0, Math.PI/30);
    ctx.strokeStyle = '#16C4CB';
    ctx.stroke();
    ctx.closePath();
    for(var i=0; i<40; i++) {
        ctx.beginPath();
        ctx.rotate(10*Math.PI/180);
        ctx.arc(0, 0, radius*2/3+4, 0, Math.PI/30);
        ctx.strokeStyle = '#16C4CB';
        ctx.stroke();
        ctx.closePath();
    }
    // 外圆环
    ctx.beginPath();
    ctx.arc(0, 0, radius-4, 0, 2*Math.PI);
    ctx.strokeStyle = '#16C4CB';
    ctx.stroke();
    ctx.closePath();
    // 数据衬着
    var data = [
        {val: chartEle.data('b'), color: '#AF4A6F'},
        {val: chartEle.data('c'), color: '#16C4CB'},
        {val: chartEle.data('d'), color: '#887BD0'},
        {val: chartEle.data('e'), color: '#19B478'},
        {val: chartEle.data('f'), color: '#DE725A'}
    ];
    // ctx.rotate(100*Math.PI/180);
    for(var j=0; j<5; j++) {
        var rate = data[j].val.split('/');
        ctx.beginPath();
        ctx.rotate(72*Math.PI/180);
        ctx.arc(0, 0, radius-4, 0, (2*Math.PI)/5*(rate[0]/rate[1]));
        ctx.strokeStyle = data[j].color;
        ctx.lineWidth = 5;
        ctx.stroke();
        ctx.closePath();
    }
</script>

觉得关注~~~~ 啦啦啦

    原文作者:zhangqh
    原文地址: https://segmentfault.com/a/1190000007571098
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞