drawing.js 2.64 KB
/*
 * @Author: yangming yangming@didihu.com.cn
 * @Date: 2023-05-17 16:07:55
 * @LastEditors: yangming yangming@didihu.com.cn
 * @LastEditTime: 2023-07-16 15:11:28
 * @FilePath: \scrm-micro-home\src\utils\drawing.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
class Drawing {
  constructor(el, canvasParams) {
    this.canvasId = el
    let { width, height } = canvasParams
    this.pixelRatio = 3
    this.ctx = this.canvasId.getContext('2d')
    width = this.toRpx(width)
    height = this.toRpx(height)
    this.canvasId.width = width
    this.canvasId.height = height
  }
  async drawImages(imageParams, callback) {
    this.ctx.beginPath()
    this.ctx.save()
    let { height, width, url, x, y } = imageParams
    height = this.toRpx(height)
    width = this.toRpx(width)
    x = this.toRpx(x)
    y = this.toRpx(y)
    let image = this.createImage()
    image.src = url
    return new Promise(resolve => {
      image.onload = () => {
        setTimeout(() => {
          this.ctx.drawImage(image, x, y, width, height)
          // 再将图片填充到画布
          let pattern = this.ctx.createPattern(image, 'no-repeat')
          this.ctx.fillStyle = pattern
          resolve(imageParams)
        }, 3000)
      }
    })
  }
  toRpx(val) {
    return this.pixelRatio * val
  }
  drawText(textParams) {
    let { fontSize, color, text, x, y, bold, font } = textParams
    fontSize = this.toRpx(fontSize)
    x = this.toRpx(x)
    y = this.toRpx(y)
    this.ctx.font = `${bold ? 'bold ' : ''}${fontSize}px ${font}`
    this.ctx.fillStyle = color
    this.ctx.textAlign = 'center'
    this.ctx.fillText(text, this.canvasId.width / 2, y + fontSize)
  }
  createImage() {
    let image = new Image()
    image.setAttribute('crossOrigin', 'Anonymous')
    return image
  }
  async begin(data = {}) {
    return new Promise(async (resolve, reject) => {
      const drawFun = () => {
        data.textList &&
          data.textList.length &&
          data.textList.map(e => {
            this.drawText(e)
          })
        console.log(this.canvasId.toDataURL('image/png'))
        resolve(this.canvasId.toDataURL('image/png'))
      }
      if (data.imageList && data.imageList.length) {
        await this.drawImages(data.imageList[0])
        if (data.imageList.length > 1)
          for (let index = 1; index < data.imageList.length; index++) {
            await this.drawImages(data.imageList[index])
            if (index == data.imageList.length - 1) drawFun()
          }
        else drawFun()
      } else drawFun()
    })
  }
}

export default Drawing