头闻号

广州龙鑫化工有限公司

沐浴液|护发素|表面活性剂|其他助剂|工业用清洗剂|硫酸盐

首页 > 新闻中心 > 科技常识:详解利用canvas实现环形进度条的方法
科技常识:详解利用canvas实现环形进度条的方法
发布时间:2024-10-04 22:34:07        浏览次数:2        返回列表

今天小编跟大家讲解下有关详解利用canvas实现环形进度条的方法 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关详解利用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基础,应该就可以了。

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

来源:爱蒂网