draw.js 8.9 KB
const _ctx_ = Symbol('_ctx_')
const _pixelRatio_ = Symbol('_pixelRatio_')
const _canvasObject_ = Symbol('_canvasObject_')
class Draw {
  [_ctx_] = null;
  [_pixelRatio_] = null;
  [_canvasObject_] = null
  constructor(_this_, canvasObject) {
    this[_canvasObject_] = canvasObject
    this[_ctx_] = _this_.ctx.getContext('2d')
    this[_pixelRatio_] = canvasObject.pixelRatio || window.devicePixelRatio || 2
    let width = this.toRpx(canvasObject.width)
    let height = this.toRpx(canvasObject.height)
    _this_.ctx.width = width
    _this_.ctx.height = height
    this[_ctx_].clearRect(0, 0, width, height)
    this[_ctx_].fillStyle = canvasObject.backgroundColor || 'rgba(255, 255, 255, 0)' || '#fff'
    this[_ctx_].fillRect(0, 0, width, height)
    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 img = new Image()
    img.src = url
    img.onload = () => {
      this[_ctx_].drawImage(img, x, y, width, height)
      this[_ctx_].restore()
      callback()
    }
  }
  toRpx(val) {
    return this[_pixelRatio_] * val
  }
  getTextWidth(text, fontSize) {
    let font = this[_ctx_].font.split('px')[1]
    if (fontSize) this[_ctx_].font = `400 ${fontSize}px${font}`
    return this[_ctx_].measureText(text).width
  }
  drawFill(x, y, width, height, color) {
    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
    let text_width = this.getTextWidth(text),
      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
    })
    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(boxX, boxY, boxWidth, boxHeight, 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(boxX, boxY, boxWidth, boxHeight, textParams.background)
    }

    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)
    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 }) {
    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))
    }
  }
  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)
  }
}
const checkTextDecoration = textDecoration => {
  return textDecoration && (textDecoration === 'underline' || textDecoration === 'overline' || textDecoration === 'line-through')
}
export default Draw