全局canvas,用于根据传入文本生成图片

69 阅读1分钟

canvas根据传入文本生成图片

代码

export function createImage(text, style = {}, canvasFontStyle = undefined) {
  var win = window
  var doc = document

  // 全局canvas,用于生成图片
  var canvas = doc.createElement('canvas')

  // var canvasFontStyle
  // var context = {
  //   $content: $('#im-content-area'),
  //   editor: this.$refs.editor,
  // }
  /**
   * 禁用alpha,否则生成的文字图片模糊
   */
  var ctx = canvas.getContext('2d', {alpha: false})
  const devicePixelRatio = win.devicePixelRatio || 1
  const backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1

  const radio = devicePixelRatio / backingStoreRatio
  // canvas.height = 16 * radio
  canvas.height = 22 * radio

  if (!canvasFontStyle) {
    // var css = win.getComputedStyle(context.$content[0])
    // canvasFontStyle = `normal normal normal ${css.getPropertyValue('font-size')}/${css.getPropertyValue('line-height')} "-apple-system", Arial, Microsoft YaHei, Microsoft JhengHei, Helvetica Neue, sans-serif`
    canvasFontStyle = 'normal normal normal 20px "-apple-system", Arial, Microsoft YaHei, Microsoft JhengHei, Helvetica Neue, sans-serif'
  }
  ctx.font = canvasFontStyle

  /**
   * 向右4px间距
   *
   * 当调用width之类时候,会重置canvas,因此下面需要重新设置字体
   */
  const width = canvas.width = radio * (ctx.measureText(text).width + 2)

  // getContext 2d的情况下 alpha参数为false避免模糊,如果是透明那就会有黑色背景色的问题,直接把背景色调整和背景一样那就是透明的效果
  ctx.fillStyle = '#f1f4f9'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  /**
   * 适配高清屏
   * @link https://gist.github.com/joubertnel/870190
   */
  if (radio > 1) {
    ctx.scale(radio, radio)
  }
  ctx.font = canvasFontStyle
  ctx.fillStyle = style.color
  ctx.textBaseline = 'middle'
  ctx.fillText(text, 0, 11)
  const url = canvas.toDataURL('image/png')
  ctx.clearRect(0, 0, canvas.width, canvas.height) // 清空上次的区域

  return {
    width: width / radio,
    url
  }
}

使用

const img = this.createImage(`${s}`, {
                color: '#ADB8BE'
                // color: '#000'
              }, `normal normal normal ${18}px "-apple-system", Arial, Microsoft YaHei, Microsoft JhengHei, Helvetica Neue, sans-serif`)