微信小程序实现番茄时钟动态画圆
时间: 2023-10-05 14:04:42 浏览: 53
要实现微信小程序中的番茄时钟动态画圆,可以使用 `<canvas>` 标签和微信小程序提供的 `wx.createCanvasContext(canvasId, this)` 方法。
首先,在小程序页面的 `.wxml` 文件中添加 `<canvas>` 标签,并设置好它的 `canvas-id` 和大小:
```html
<canvas canvas-id="circle" style="width: 300px; height: 300px;"></canvas>
```
然后,在页面的 `.js` 文件中,获取 `<canvas>` 标签的上下文对象,并使用 `draw()` 方法在 `<canvas>` 中绘制圆形:
```javascript
Page({
data: {
percent: 0, // 圆形的百分比
},
// 获取 <canvas> 标签的上下文对象
onReady: function () {
this.ctx = wx.createCanvasContext('circle', this);
},
// 绘制圆形
drawCircle: function () {
// 获取圆形的半径和圆心坐标
const r = 100; // 半径
const x = 150; // 圆心横坐标
const y = 150; // 圆心纵坐标
// 绘制圆形的底色
this.ctx.beginPath();
this.ctx.arc(x, y, r, 0, 2 * Math.PI);
this.ctx.setStrokeStyle('#efefef');
this.ctx.setLineWidth(10);
this.ctx.stroke();
// 绘制圆形的进度条
this.ctx.beginPath();
this.ctx.arc(x, y, r, -Math.PI / 2, this.data.percent * 2 * Math.PI - Math.PI / 2);
this.ctx.setStrokeStyle('#ff5b5b');
this.ctx.setLineWidth(10);
this.ctx.stroke();
// 绘制圆形的百分比文字
this.ctx.setFillStyle('#666');
this.ctx.setFontSize(30);
this.ctx.setTextAlign('center');
this.ctx.setTextBaseline('middle');
this.ctx.fillText(`${this.data.percent * 100}%`, x, y);
},
// 更新圆形的百分比
updatePercent: function () {
const interval = setInterval(() => {
if (this.data.percent === 1) {
clearInterval(interval);
return;
}
this.data.percent += 0.01;
this.drawCircle();
}, 25);
},
// 点击事件,开始动态绘制圆形
start: function () {
this.updatePercent();
},
})
```
在上述代码中,`drawCircle()` 方法用于绘制圆形,其中 `this.data.percent` 表示圆形的百分比,初始值为 0。`updatePercent()` 方法用于不断更新 `this.data.percent` 的值,并调用 `drawCircle()` 方法进行绘制,从而实现动态画圆的效果。
最后,在 `.wxml` 文件中添加按钮,并绑定 `start()` 方法:
```html
<button bindtap="start">开始</button>
```
点击按钮后,就会开始动态绘制圆形。