微信小程序,canvas 15秒 画一个圆,支持暂停、开启

小程序中可能会遇到需要画一个类似于计时器的圆,这里是一个 demo,可以拿走根据自己的业务需求进行调整。

代码比较简单,重点还是写代码的时候注意几点原则吧:

1,每个方法不要超过30行

2,有重复的逻辑,考虑抽取共有方法

3,初始化的变量,可以不设置,使用默认值

wxml代码

<canvas style="width:200px; height:200px;" canvas-id="myCanvas"></canvas>
<view bindtap="startOrStopDraw">{
   
   {drawActive}}</view>

js代码

var app = getApp();

var drawInterval = false;
Page({
  data: {
    drawActiveArr:['STOP', 'START'],
    start: - Math.PI / 2,
    stop: - Math.PI / 2,
    drawIndex: 1 //默认按钮处于 点击开始画圆 状态
  },
  
  onLoad: function (options) {
    this.myCanvas();//画布
  },
  /** 画布 开始*/ 
  startOrStopDraw: function(){
    //依次动作:停止画圆、开始画圆
    var index = this.data.drawIndex;
    // if(index > 0){
    //   //开始
    //   this.draw();
    // }else{
    //   //停止
    //   if (drawInterval){
    //     clearInterval(drawInterval);
    //   }
    // }
    //上面 if 判断流程的缩减写法
    index > 0 ? this.draw() : drawInterval ? clearInterval(drawInterval) : false;
    index = (index + 1) % 2;
    this.setDrawActiveData(index);
  },
  init: function(){
    this.setDrawActiveData(this.data.drawIndex ? this.data.drawIndex : 0);
  },
  setDrawActiveData: function (drawIndex){
    this.setData({
      drawActive: this.data.drawActiveArr[drawIndex], 
      drawIndex: drawIndex
    });
  },

  myCanvas: function(){
    this.init();
    // this.draw();
  },
  // 获取 stop 值,然后计算下一帧的值,再继续画
  // 15 s 画一圈 15 000 = 40 * 375
  draw: function (){
    const ctx = wx.createCanvasContext('myCanvas');
    var x = 100, y = 100, r = 50;
    var start = this.data.start;
    var stop = this.data.stop; 
    var _this = this;
    var callback = function () {
      stop += (2 * Math.PI) / 375
      stop = _this.getStop(stop);
      _this.setStop(stop);
      _this.myDraw(ctx, x, y, r, start, stop);
    }
    drawInterval = setInterval(callback, 40);
  },
  setStop: function(stop){
    this.setData({
      stop: stop
    });
  },
  getStop: function(stop){
    return stop > (2 * Math.PI - Math.PI / 2) ? (2 * Math.PI) / 150 - Math.PI / 2 : stop;
  },
  myDraw: function(ctx, x, y, r, start, stop){
    ctx.arc(x, y, r, start, stop);
    ctx.setStrokeStyle('#0cc');
    ctx.setLineWidth(5);
    ctx.stroke();
    ctx.draw();
  }
  /** 画布 结束*/
})

猜你喜欢

转载自blog.csdn.net/u013276512/article/details/90715814