微信小程序canvas实现圆形计时器功能

index.js

import Canvas from '../../utils/canvas.js'
Page({
...Canvas.options,
/**
* 页面的初始数据
*/
data: {
...Canvas.data,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this=this;
// setTimeout(function(){

// },1000)

},
start: function (event){
this.draw('runCanvas', 9, 1000);
},
stop: function (event){
this.stoppp();
}
})

index.xml

<view class='canvasBox'>
<view class='bigCircle'></view>
<view class='littleCircle'></view>
<canvas canvas-id="runCanvas" id="runCanvas" class='canvas'></canvas>

<view bindtap='start'>
开始
</view>
<view bindtap='stop'>
停止
</view>
</view>

canvas.js

export default {
data: {
percentage: '', //百分比
animTime: '', // 动画执行时间
time:null
},
options: {
// 绘制圆形进度条方法

run(c, w, h) {
let that = this;
let hs=0;
let timer = null;


var num = (2 * Math.PI / 100 * c) - 0.5 * Math.PI;
var bottomC = Math.PI;
that.data.ctx2.arc(w, h, w - 8, 0.8 * Math.PI, num-1.9)
that.data.ctx2.setStrokeStyle("#ff5000");
that.data.ctx2.setLineWidth("16");
that.data.ctx2.setLineCap("butt");
that.data.ctx2.stroke();
that.data.ctx2.beginPath();
that.data.ctx2.setFontSize(40); //注意不要加引号
that.data.ctx2.setFillStyle("#fff000");
that.data.ctx2.setTextAlign("center");
that.data.ctx2.setTextBaseline("middle");


var mess = '';
if (c < 10) {
c = '0:' + '0' + c
} else {
c = '0:' + c
}

that.data.ctx2.fillText(c , w, h);
that.data.ctx2.draw();
},
/**
* start 起始百分比
* end 结束百分比
* w,h 其实就是圆心横纵坐标
*/
// 动画效果实现
canvasTap(start, end, time, w, h) {
var that = this;
clearInterval(that.data.time);


that.data.time=setInterval(function(){
that.canvasTap(start, end, time, w, h);
that.run(start, w, h);
},1000)

start++;
console.log('start' + start)
if (start > 60) {
clearInterval(that.data.time);
return false;
}

},
/**
* id----------------canvas画板id
* percent-----------进度条百分比
* time--------------画图动画执行的时间 
*/
draw: function (id, percent, animTime) {
var that = this;
const ctx2 = wx.createCanvasContext(id);
that.setData({
ctx2: ctx2,
percentage: percent,
animTime: animTime
});
var time = that.data.animTime / that.data.percentage;
wx.createSelectorQuery().select('#' + id).boundingClientRect(function (rect) { //监听canvas的宽高
var w = parseInt(rect.width / 2); //获取canvas宽的的一半
var h = parseInt(rect.height / 2); //获取canvas高的一半,
that.canvasTap(0, that.data.percentage, time, w, h)
}).exec();
},
stoppp:function(event){
var that=this;
clearInterval(that.data.time);
}
}
}
原文地址:https://www.cnblogs.com/h5it/p/10760445.html