用es6的class类单例模式封装canvas环形进度条

项目中需要一个请求进度效果,尝试了下自己用 canvas 来绘制一个环形进度条,动效直接用的休眠函数加随机数来模拟。用到了 es6 里的 class 类,用单例模式的懒汉模式来实例化对象,不像 Java 这种纯面向对象的语言,写着还是有点别扭。


1.png
import NP from 'number-precision'

/**
 * 休眠函数
 * @param {Number} wait
 */
function sleep(wait) {
  return new Promise((resolve) => {
    setTimeout(resolve, wait)
  })
}

export default class CanvasProgress {
  constructor({ elementId, height = 200, width = 200 }) {
    if (elementId) {
      this.canvas = document.getElementById(elementId) // canvas 节点
      this.canvas.height = height
      this.canvas.width = width
      this.elementId = elementId
      this.height = height
      this.width = width
      this.cxt = canvas.getContext('2d') // 绘图上下文
    }

    // this.instance = null
    this.reset()
  }

  /**
   * 设置进度
   * @param {boolean} value
   */
  setStep(value) {
    this.step = value
  }

    /**
   * 设置是否暂停
   * @param {boolean} value
   */
  setIsPause(value) {
    this.isPause = value
  }

  /**
   * 设置是否结束
   * @param {boolean} value
   */
  setIsEnd(value) {
    this.isEnd = value
  }

  /**
   * 重置
   */
  reset() {
    this.setStep(0)
    this.setIsPause(false)
    this.setIsEnd(false)
  }

  /**
   * 获取实例,单例模式
   * @param {Object} config
   * @returns {CanvasProgress} 实例对象
   */
  static getInstance(config) {
    const { elementId, height, width } = config

    // 这里比较要用 instance 实例,不能直接用 this
    const ins = this.instance
    if (!ins || (ins && (elementId !== ins.elementId || height !== ins.height || width !== ins.width))) {
      this.instance = new CanvasProgress(config)
    }
    return this.instance
  }

  /**
   * 初始化
   * @param {string} e 初始化类型:restart-重启
   */
  async init(e) {
    const restart = e === 'restart'
    let isStarted = false // 是否已经开启了
    let isPaused = false // 是否已经暂停了

    if (!restart) {
      isStarted = this.step > 0
      isPaused = this.isPause || this.step === 100
      this.reset()
    }

    this.start({ isStarted, isPaused })
  }

  /**
   * 开启
   * @param {boolean} param.isStarted 是否已经开启,若开启了只用修改 step 数据,继续使用开启的 while 循环
   * @param {boolean} param.isPaused 是否已经暂停,若暂停了需重新开启 while 循环
   */
  async start({ isStarted, isPaused } = {}) {
    while( this.step < 100) {
      if (this.isPause) return
      if (isStarted) {
        if (isPaused) this.start() // 暂停了的要重新开启个循环
        return
      }

      if (this.isEnd) {
        await sleep(50)

        this.step = parseInt(this.step)
        if (this.step < 100) {
          this.step++
        }
        this.draw()
        continue
        // return
      }

      // 生成 1-9之间的随机数
      const random = Math.round(Math.random() * 8) + 1
      const num = NP.divide(random, Math.pow(10, random))

      if (this.step < 80) {
        await sleep(100)
        this.step = NP.plus(this.step, (random > 5 ? random - 5 : random))
      } else if (this.step >= 80 && this.step < 99.98) {
        await sleep(10 * random)
        this.step = NP.plus(this.step, num).toFixed(2)
      } else {
        // 接口还没返回数据要处理下,否则无限死循环会内存溢出
        // await sleep(1000)
        // continue
        // 直接 return 或暂停了,成功时再重启
        this.pause()
      }

      // 大于100时修正
      if (this.step > 100) this.step = 100
      this.draw()
    }
  }

  /**
   * 暂停
   */
  pause() {
    this.setIsPause(true)
  }

  /**
   * 重启
   */
  restart() {
    this.setIsPause(false)
    this.init('restart')
  }

  /**
   * 结束
   */
  end() {
    this.setIsEnd(true)
    if (this.isPause) this.restart()
  }

  /**
   * 绘图
   */
  draw() {
    this.clearRect()

    const x = this.width / 2
    const y = this.height / 2

    // 灰色背景
    this.cxt.beginPath()
    this. cxt.moveTo(x, y)
    this.cxt.arc(x, y, x, 0, Math.PI * 2)
    this.cxt.fillStyle='#ddd'
    this.cxt.fill()
    this.cxt.closePath()

    // 进度
    this.cxt.beginPath()
    this.cxt.moveTo(100,100)
    // arc(圆的中心x坐标, 圆的中心y坐标, 圆半径, 起始角, 结束角[, 逆/顺时针])
    this.cxt.arc(x, y, x, -Math.PI * 0.5, Math.PI * 2 * this.step / 100 - Math.PI * 0.5, false)
    this.cxt.fillStyle='#57bc78'
    this.cxt.fill()
    this.cxt.closePath()

    // 顶层中间白色圆圈遮挡
    this.cxt.beginPath()
    this.cxt.moveTo(x, y)
    this.cxt.arc(x, y, 80, 0, Math.PI * 2)
    this.cxt.fillStyle="#fff"
    this.cxt.fill()
    this.cxt.closePath()

    // 文字
    this.cxt.textAlign = 'center'
    this.cxt.fillStyle='#57bc78'
    this.cxt.textBaseline = 'middle'
    this.cxt.font = 'bold 24px Arial'
    this.cxt.fillText(this.step + '%', x, y)
  }

  /**
   * 清除绘图区域
   */
  clearRect() {
    this.cxt.clearRect(0, 0, this.width, this.height)
  }

  /**
   * 保存图片
   */
  saveImg() {
    const url = this.canvas.toDataURL()
    let a = document.createElement('a')
    a.setAttribute('href', url)
    a.setAttribute('download', 'img.png')
    a.setAttribute('target', '_blank')
    document.body.appendChild(a)
    a.dispatchEvent(new MouseEvent('click'))
    document.body.removeChild(a)
  }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,478评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,825评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,482评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,726评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,633评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,018评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,168评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,320评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,264评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,288评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,995评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,587评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,909评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,284评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,862评论 2 339

推荐阅读更多精彩内容