drawing.js 2.26 KB
/*
 * @Author: yangming yangming@didihu.com.cn
 * @Date: 2023-05-17 16:07:55
 * @LastEditors: yangming yangming@didihu.com.cn
 * @LastEditTime: 2023-05-30 12:57:42
 * @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
    const { width, height } = canvasParams
    this.canvasId.width = width
    this.canvasId.height = height
    this.ctx = this.canvasId.getContext('2d')
  }
  async drawImages(imageParams, callback) {
    this.ctx.beginPath()
    this.ctx.save()
    let { height, width, url, x, y } = imageParams
    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)
      }
    })
  }
  drawText(textParams) {
    const { fontSize, color, text, x, y } = textParams
    console.log(x, y)
    this.ctx.font = `${fontSize}px Calibri`
    this.ctx.fillStyle = color
    this.ctx.fillText(text, x, 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