h5圆形进度条

来源:互联网 发布:免流量软件下载 编辑:程序博客网 时间:2024/06/07 17:13


组件封装文件 circlebar.js   代码如下:

(function() {
var context, centerX, centerY;
var rad = Math.PI * 2 / 100; //将360度分成100份,每份为rad度
var radius = 25; //默认半径
var lineWidth = 5; //默认线宽
var speed = 0; //默认初始加载值
var value = 0;


//绘制有值的颜色圈环
function valueCircle(n) {
context.save();
context.strokeStyle = "#19AC55"; //设置描边样式
context.lineWidth = lineWidth; //设置线宽
context.beginPath(); //路径开始
context.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + n * rad, false); //用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
context.stroke(); //绘制
context.closePath(); //路径结束
context.restore();
}
//绘制背景圆环圈
function bgCircle() {
context.save();
context.beginPath();
context.lineWidth = lineWidth; //设置线宽
context.strokeStyle = "#ECEAE9";
context.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
context.restore();
}
//百分比文字绘制
function text(n) {
context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
context.strokeStyle = "#ECEAE9"; //设置描边样式
context.font = "bold 17px Arial"; //设置字体大小和字体
//绘制字体,并且指定位置
context.fillStyle = "#19AC55";
context.fillText(n.toFixed(0) + "%", centerX - 18, centerY + 5);
context.stroke(); //执行绘制
context.restore();
}


var circlebar = function(id, v, radi, lWidth) {


var canvas = document.getElementById(id); //获取canvas元素
centerX = canvas.width / 2; //Canvas中心点x轴坐标
centerY = canvas.height / 2; //Canvas中心点y轴坐标


if(v) {
value = v;
}
if(radi) {
radius = radi;
}
if(lWidth) {
lineWidth = lWidth;
}


context = canvas.getContext('2d'); //获取画图环境,指明为2d
//动画循环
(function drawFrame() {
if(speed < value) {
window.requestAnimationFrame(drawFrame);
}
context.clearRect(0, 0, canvas.width, canvas.height);
bgCircle();


text(speed);
valueCircle(speed);
//if(speed > 100) speed = 0;
speed += 1;
}());
}
window.circlebar = circlebar;
})();


使用方法:

1.在对应html引入circlebar.js文件;

2.在对应div添加  如:

<div>
<canvas id="canvas" width="260px" height="260px"></canvas>
</div>

注意: canvas的width和height属性值不得小于直径和条形宽度之和。

3.在<script> 里面 添加 new circlebar("canvas",70);  //此处设置的进度值为70,半径和条形宽度为默认值,分别为25 、5.




原创粉丝点击