canvas环形倒计时组件的示例代码

2019-01-28 11:55:11王旭
ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = "#fff"; // ctx.fillText(文字,相对画布的X坐标,相对画布的Y坐标) ctx.fillText(30, size / 2, size / 2);

5.如何制作动画?其实也是画白色圆的过程,慢慢的覆盖黄色进度条的过程,那么先把白色的圆画出来出来,这个时候蓝圆就会被白色的动画圆给盖住,这个时候最后画蓝圆就好了。

let deg = Math.PI / 180; ctx.beginPath(); // tcx.arc(圆心X,圆心Y,半径,起始角度,结束角度,顺逆时针); ctx.arc(size / 2, size / 2, size / 2-4, 0* deg, 360 * deg, false); ctx.fillStyle = "#fff"; ctx.fill(); ctx.closePath();

6.比较简单的绘画过程完成了,接下来要将动画和数字关联起来,利用当前的最新时间-最开始的时间,再除总的时间可以得到一个关键的百分比,这个百分比决定数字的变化,以及白色动画圆绘制的角度。

Countdown.prototype.countdown = function () { let oldTime = +new Date();// 过去的时间:1522136419291 timer = setInterval(() => { let currentTime = +new Date();// 现在的时间:1522136419393 let allMs = this.settings.time * 1000;// 总时间豪秒数:如30*1000=30 000ms schedule = (currentTime - oldTime) / allMs;// 绘制百分比:(1522136419393-1522136419291)/30000=0.0204 this.schedule = schedule; this.drawAll(schedule); if (currentTime - oldTime >= allMs) { // 重绘 this.drawBackground(); this.drawProcess(); this.drawAnimate(); this.drawInner(); this.strokeText(0); clearInterval(timer); } }, 10); }; // 绘制所有 Countdown.prototype.drawAll = function (schedule) { schedule = schedule >= 1 ? 1 : schedule; let text = parseInt(this.settings.time * (1 - schedule)) + 1; // 清除画布 this.ctx.clearRect(0, 0, this.settings.size, this.settings.size); this.drawBackground(); this.drawProcess(); this.drawAnimate(); this.drawInner(); this.strokeText(text); }; // 绘制进度条动画 Countdown.prototype.drawAnimate = function () { // 旋转的角度 let deg = Math.PI / 180; let v = schedule * 360, startAng = -90,// 开始角度 endAng = -90 + v;// 结束角度 this.ctx.beginPath(); this.ctx.moveTo(this.settings.size / 2, this.settings.size / 2); this.ctx.arc(this.settings.size / 2, this.settings.size / 2, this.settings.size / 2 - 3, startAng * deg, endAng * deg, false); this.ctx.fillStyle = this.settings.scheduleColor; this.ctx.fill(); this.ctx.closePath(); };