Draw.js 10.8 KB
const _ctx_ = Symbol('_ctx_')
const _pixelRatio_ = Symbol('_pixelRatio_')
const _canvasObject_ = Symbol('_canvasObject_')
const _canvas_ = Symbol('_canvas_')
class Draw {
  [_ctx_] = null;
  [_pixelRatio_] = null;
  [_canvasObject_] = null;
  [_canvas_] = null
  constructor(canvasObject) {
    wx.getSystemInfo().then(({ pixelRatio }) => {
      // console.log(pixelRatio)
      this[_canvasObject_] = canvasObject
      this[_pixelRatio_] = canvasObject.pixelRatio || pixelRatio || 2
      const height = this.toRpx(canvasObject.height),
        width = this.toRpx(canvasObject.width),
        canvas = wx.createOffscreenCanvas({
          type: '2d',
          width,
          height
        }),
        ctx = canvas.getContext('2d')
      this[_canvas_] = canvas
      this[_ctx_] = ctx
      this[_ctx_].clearRect(0, 0, width, height)
      this.drawFill({
        x: 0,
        y: 0,
        width,
        height,
        color: canvasObject.backgroundColor || 'rgb(255, 255, 255)'
      })
      this[_ctx_].save()
    })
  }
  drawImages(imageParams, callback) {
    this[_ctx_].beginPath()
    this[_ctx_].save()
    let { borderRadius, height, width, url, x, y } = imageParams
    height = this.toRpx(height)
    width = this.toRpx(width)
    x = this.toRpx(x)
    y = this.toRpx(y)
    if (borderRadius) {
      this.drawRadiusRect({
        borderRadius,
        height,
        width,
        x,
        y
      })
      this[_ctx_].clip()
    }
    let image = this[_canvas_].createImage()
    new Promise(resolve => {
      image.onload = resolve
      image.src = `${url}?v=${Date.now()}`
    }).then(() => {
      this[_ctx_].drawImage(image, x, y, width, height)
      this[_ctx_].restore()
      if (callback) callback()
    })
  }
  toRpx(val) {
    return this[_pixelRatio_] * val
  }
  getTextWidth(text, fontSize) {
    let font = this[_ctx_].font.split('px')[1]
    if (fontSize) this[_ctx_].font = `${fontSize}px${font}`
    return this[_ctx_].measureText(text).width
  }
  drawFill({ x, y, width, height, color }) {
    height = this.toRpx(height)
    width = this.toRpx(width)
    x = this.toRpx(x)
    y = this.toRpx(y)
    this[_ctx_].beginPath()
    this[_ctx_].fillStyle = color
    this[_ctx_].fillRect(x, y, width, height)
    this[_ctx_].stroke()
    this[_ctx_].restore()
    this[_ctx_].save()
  }
  drawText(textParams) {
    let { textDecoration, textBaseline, lineHeight, fontWeight, textAlign, textWidth, maxWidth, fontSize, lastFont, opacity, lineNum, width, color, text, x, y } = textParams,
      font = this[_ctx_].font.split('px')[1]
    textAlign = textAlign || 'left'
    textBaseline = textBaseline || 'normal'
    opacity = typeof opacity === 'number' ? opacity : 1
    lineHeight = this.toRpx(lineHeight || fontSize || 12)
    textWidth = this.toRpx(textWidth || 0)
    fontSize = this.toRpx(fontSize || 12)
    maxWidth = this.toRpx(maxWidth || width || this[_canvasObject_].width)
    width = this.toRpx(width || this[_canvasObject_].width)
    x = this.toRpx(x)
    y = this.toRpx(y)
    let fontX = this.getFontWidth({
      textAlign,
      fontSize,
      text,
      x
    })
    this[_ctx_].beginPath()
    this[_ctx_].globalAlpha = opacity
    this[_ctx_].font = `${fontWeight || 400} ${fontSize}px${font}`
    this[_ctx_].fillStyle = color || '#000'
    this[_ctx_].strokeStyle = color || '#000'
    this[_ctx_].textBaseline = textBaseline
    this[_ctx_].textAlign = textAlign
    this[_ctx_].lineWidth = this.toRpx(2)
    let text_width = this.getTextWidth(text)
    if (textParams.border) {
      let boxX = this.toRpx(textParams.x - 4.5),
        boxY = this.toRpx(textParams.y - 0.5),
        boxWidth = text_width + this.toRpx(9),
        boxHeight = lineHeight + this.toRpx(4)
      if (boxWidth > width - fontX - this.getTextWidth('…') - fontSize) {
        boxWidth = width - boxX + this.toRpx(9)
      }
      this.drawFill({
        x: boxX,
        y: boxY,
        width: boxWidth,
        height: boxHeight,
        color: textParams.border
      })
    }
    if (textParams.background) {
      let boxX = this.toRpx(textParams.x - 4),
        boxY = this.toRpx(textParams.y),
        boxWidth = text_width + this.toRpx(8),
        boxHeight = lineHeight + this.toRpx(3)
      if (boxWidth > width - fontX - this.getTextWidth('…') - fontSize) {
        boxWidth = width - boxX + this.toRpx(8)
      }
      this.drawFill({
        x: boxX,
        y: boxY,
        width: boxWidth,
        height: boxHeight,
        color: textParams.background
      })
    }
    const drawOneLineText = () => {
      let textArr = text.toString().split(''),
        newText = '',
        ellipsis = false
      try {
        textArr.map(e => {
          newText += e
          if (this.getTextWidth(newText) > width - fontX) throw true
        })
      } catch (error) {
        ellipsis = error
      }
      if (ellipsis) newText += '…'
      if (lastFont) newText += lastFont
      this[_ctx_].fillText(newText, x, y, maxWidth)
      if (checkTextDecoration(textDecoration)) {
        this.drawDecoration({
          textDecoration,
          textBaseline,
          textAlign,
          fontSize,
          newText,
          opacity,
          text,
          y,
          x
        })
      }
    }
    if (lineNum > 1) {
      let textArr = text.split(''),
        textRowArr = [],
        currentText = '',
        viewWidth = width - fontX
      if (text_width > viewWidth) {
        textArr.map(e => {
          currentText += e
          if (this.getTextWidth(currentText) >= viewWidth && textRowArr.length < lineNum - 1) {
            textRowArr.push(currentText)
            currentText = ''
          }
        })
        if (currentText.length) textRowArr.push(currentText)
        textRowArr.map((e, index) => {
          if (this.getTextWidth(e) > viewWidth && index == lineNum - 1) {
            try {
              let lastText = '',
                lastArr = e.split('')
              lastArr.map(i => {
                lastText += i
                if (this.getTextWidth(lastText) > width - fontX - this.getTextWidth('…')) throw lastText
              })
            } catch (error) {
              if (lastFont) e = `${error.substring(0, error.length - lastFont.length)}…${lastFont}`
              else e = `${error}…`
            }
          }
          if (lastFont && e.indexOf(lastFont) == -1 && textRowArr.length < 2) e = `${e.substring(0, e.length - lastFont.length)}…${lastFont}`
          let textHeight = y + index * (lineHeight || fontSize)
          this[_ctx_].fillText(e, x, textHeight, maxWidth)
          if (checkTextDecoration(textDecoration)) {
            this.drawDecoration({
              y: textHeight,
              textDecoration,
              textBaseline,
              textAlign,
              fontSize,
              newText: e,
              opacity,
              text,
              x
            })
          }
        })
      } else {
        drawOneLineText()
      }
    } else {
      drawOneLineText()
    }

    this[_ctx_].stroke()
  }
  drawLine(lineParams, callback) {
    this[_ctx_].beginPath()
    let { opacity, startX, startY, width, color, endX, endY } = lineParams
    startX = this.toRpx(startX)
    startY = this.toRpx(startY)
    width = this.toRpx(width)
    endX = this.toRpx(endX)
    endY = this.toRpx(endY)
    this[_ctx_].globalAlpha = typeof opacity === 'number' ? opacity : 1
    this[_ctx_].strokeStyle = color || '#000'
    this[_ctx_].lineWidth = width || this.toRpx(1)
    this[_ctx_].moveTo(startX, startY)
    this[_ctx_].lineTo(endX, endY)
    this[_ctx_].stroke()
    this[_ctx_].restore()
    this[_ctx_].save()
    if (callback) callback()
  }
  setLineY = params => {
    let { textDecoration, textBaseline, fontSize, y } = params
    let type = {
      underline: {
        top: y + fontSize,
        middle: y + fontSize / 2,
        bottom: y,
        normal: y
      },
      overline: {
        top: y,
        middle: y - fontSize / 2,
        bottom: y - fontSize,
        normal: y
      },
      'line-through': {
        top: y + fontSize / 2,
        middle: y - fontSize / 2,
        bottom: y,
        normal: y
      }
    }
    return type[textDecoration][textBaseline]
  }

  setLineX({ textAlign, text, x }) {
    let textWidth = this.getTextWidth(text)
    let type = {
      left: x,
      center: x - textWidth / 2,
      right: x - textWidth
    }
    return type[textAlign]
  }

  drawRadiusRect({ borderRadius, height, width, x, y }, callBack) {
    let radius = typeof borderRadius === 'string' ? ((Number(borderRadius.split('%')[0]) / 100) * width) / 2 : borderRadius / 2
    radius = radius || 0
    this[_ctx_].beginPath()
    for (let i = 1; i < 5; i++) {
      let arcX = i === 1 || i === 4 ? x + width - radius : x + radius
      let arcY = i === 1 || i === 2 ? y + height - radius : y + radius
      this[_ctx_].arc(arcX, arcY, radius, 2 * Math.PI * ((i - 1) / 4), 2 * Math.PI * (i / 4))
    }
    if (callBack) callBack()
  }
  getFontWidth({ textAlign, fontSize, text, x }) {
    let type = {
      left: x,
      center: x - (fontSize * text.length) / 2,
      right: x - fontSize * text.length
    }
    return type[textAlign] < 0 ? 0 : type[textAlign]
  }

  drawDecoration(params) {
    let { newText, opacity, y, x } = params
    let lineX = x
    let lineY = y
    lineX = this.setLineX(params)
    lineY = this.setLineY(params)
    this[_ctx_].globalAlpha = opacity
    this[_ctx_].moveTo(lineX, lineY)
    this[_ctx_].lineTo(lineX + this.getTextWidth(newText), lineY)
  }
  toDataURL(callBack) {
    let url = this[_canvas_].toDataURL('image/png')
    const base64src = function (base64data) {
      return new Promise((resolve, reject) => {
        const [a, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []
        if (!format) reject(new Error('ERROR_BASE64SRC_PARSE'))
        const filePath = `${wx.env.USER_DATA_PATH}/tmp_base64src.${format}`
        const buffer = wx.base64ToArrayBuffer(bodyData)
        wx.getFileSystemManager().writeFile({
          filePath,
          data: buffer,
          encoding: 'binary',
          success() {
            resolve(filePath)
          },
          fail() {
            reject(new Error('ERROR_BASE64SRC_WRITE'))
          }
        })
      })
    }
    base64src(url).then(img => {
      console.log('img', img)
      createLocalImg(img, callBack)
    })
  }
}
const checkTextDecoration = textDecoration => {
  return textDecoration && (textDecoration === 'underline' || textDecoration === 'overline' || textDecoration === 'line-through')
}

/**网络图片转成本地资源 */
const createLocalImg = (url, callBack) => {
  wx.getImageInfo({
    src: url,
    success(res) {
      callBack(res)
    },
    fail() {
      wx.showToast({
        title: '图片生成失败,请稍后再试',
        icon: 'none'
      })
      wx.hideLoading()
      console.error(`图片转换本地失败,${url}`)
    }
  })
}
export default Draw