标签:
最近研究了下环形百分图如何用前端实现的,查了资料总结了以下2种方法,用多层div和canvas,
实例地址:http://play.163.com/special/tese-circle/
一:用多层div实现
需要三个层绝对定位,当中的2个层分别用clip盖住左边和右边,控制旋转角度,漏出最底部有颜色的环实现,附上代码:
.circle {width: 200px;height: 200px;position: relative;border-radius: 50%;background: #00b0f0;}
.pie_left, .pie_right {width: 200px;height: 200px;position: absolute;top: 0;left: 0;}
.left, .right {display: block;width:200px; height:200px;background:#bfbfbf;border-radius: 50%;position: absolute;top: 0;left: 0;}
.pie_right , .right{clip:rect(0,auto,auto,100px);}
.pie_left, .left {clip:rect(0,100px,auto,0);}
.mask {width: 150px;height: 150px;border-radius: 50%;left: 25px;top: 25px;background: #FFF;position: absolute;text-align: center;line-height: 150px;font-size: 20px;font-weight: bold;}
<div class="circle" data-num="25">
<div class="pie_left">
<div class="left"></div>
</div>
<div class="pie_right">
<div class="right"></div>
</div>
<div class="mask">
<span>25</span>
%
</div>
</div>
function showCircle(){
$(‘.circle‘).each(function(index, el) {
var num = $(this).find(‘span‘).text() * 3.6;
if (num<=180) {
$(this).find(‘.right‘).css(‘transform‘, "rotate(" + num + "deg)");
} else {
$(this).find(‘.right‘).css(‘transform‘, "rotate(180deg)");
$(this).find(‘.left‘).css(‘transform‘, "rotate(" + (num - 180) + "deg)");
};
});
}
二:用canvas实现
<div class="circular" data-percent="25">
<canvas class="cvs" width="60" height="60"></canvas>
<span class="num">25</span>
</div>
function drawcanvas(){
$(‘.circular‘).each(function(index, el) {
var p = $(el).attr(‘data-percent‘);
var angle = Math.PI*2*(p/100)-Math.PI/2;
var cvs = $(el).find(‘.cvs‘);
var cxt=cvs[0].getContext("2d");
cxt.lineWidth=5;
cxt.strokeStyle="green";
cxt.beginPath();
cxt.arc(30,30,20,-Math.PI/2,angle,false);//顺时针,默认从3点钟方向开始
cxt.stroke();//画空心圆
})
}
参考网址:
网上插件:
网上插件:easypiechart.js
canvas : http://www.365mini.com/page/html5-canvas-circle.htm
div :http://codepen.io/anon/pen/JXqNvW
标签:
原文地址:http://www.cnblogs.com/huangxiaowen/p/5546685.html