详解利用canvas实现环形进度条的方法

前提:有时候在项目中会有用到进度条的情况,使用css3也可以实现,但是对于性能不好的设备,或者网络不好的情况下,卡顿现象非常明显,避免出现不流畅的尴尬情况,所以记录一下,使用canvas来实现的方法。

效果图

DOM中,首先定义canvas画板元素:

<canvas id="canvas" width="500" height="500" style="background:#F7F7F7;">    <p>you browser not support canvas!</p>  </canvas>

对于不支持canvas的浏览器则会显示:you browser not support canvas!

接下来是js编写:

定义canvas.js并在页面引入

var canvas = document.getElementById('canvas'), //获取canvas元素  context = canvas.getContext('2d'), //获取画图环境,指明为2d  centerX = canvas.width / 2, //Canvas中心点x轴坐标  centerY = canvas.height / 2, //Canvas中心点y轴坐标  rad = Math.PI * 2 / 100, //将360度分成100份,那么每一份就是rad度  speed = 0.1; //加载的快慢就靠它了//绘制蓝色外圈function blueCircle(n) {  context.save();  context.beginPath();  context.strokeStyle = "#49f";  context.lineWidth = 12;  context.arc(centerX, centerY, 100, -Math.PI / 2, -Math.PI / 2 + n * rad, false);  context.stroke();  context.restore();}//绘制白色外圈function whiteCircle() {  context.save();  context.beginPath();  context.strokeStyle = "#A5DEF1";  context.lineWidth = 12;  context.arc(centerX, centerY, 100, 0, Math.PI * 2, false);  context.stroke();  context.closePath();  context.restore();}//百分比文字绘制function text(n) {  context.save();  context.fillStyle = "#F47C7C";  context.font = "40px Arial";  context.textAlign = "center";  context.textBaseline = "middle";  context.fillText(n.toFixed(0) + "%", centerX, centerY);  context.restore();}//动画循环(function drawFrame() {  window.requestAnimationFrame(drawFrame, canvas);  context.clearRect(0, 0, canvas.width, canvas.height);  whiteCircle();  text(speed);  blueCircle(speed);  if (speed > 100) speed = 0;  speed += 0.1;}());window.requestAnimationFrame(drawFrame, canvas);

每行代码的注释标注非常清楚,如果还有不理解的可以去看canvas基础,应该就可以了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

发表新评论