收藏
回答

canvas 2d 海报绘图顺序问题 ?

使用 canvas 2d 生成海报,开发者工具 & 安卓真机正常,iOS上绘制文字的区域空白,

经测试发现文字绘制成功,但是是在海报最底层,被图片覆盖,有什么兼容处理的方法吗?

伪代码如下

// 绘制图片
  wxDrawImage() {
    let {
      canvasWidth,
      canvasHeight,
      detailImg,
      maskTop,
      bgImgPath,
      avatarImg,
      QRImg
    } = this.state
    let self = this


    this.refs.shareCanvas.fields({ node: true, size: true }).exec(async res => {
      const canvas = res[0].node
      const ctx = canvas.getContext('2d')


      canvas.width = 750
      canvas.height = 1333


      await drawImage(canvas, ctx, self)
    })


    async function drawImage(canvas, ctx, self) {
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, canvasWidth, canvasHeight)


      await drawImageItem(canvas, ctx, detailImg, 0, 0, 750, 526)
      await drawImageItem(canvas, ctx, maskTop, 0, 0, 750, 526)
      await drawImageItem(canvas, ctx, bgImgPath, 18, 328, 726, 1000)
      await drawImageItem(canvas, ctx, QRImg, 538, 1090, 141, 160)
      let avatarInfo = await Taro.getImageInfo({ src: avatarImg })
      if (avatarInfo.width && avatarInfo.height) {
        const img = canvas.createImage()
        img.src = avatarImg
        img.onload = () => {
          ctx.beginPath()
          ctx.arc(55, 113, 25, 0, Math.PI * 2)
          ctx.clip()
          ctx.drawImage(img, 30, 88, 50, 50)
        }
      } else {
        fail()
      }


      // 日期
      ctx.fillStyle = '#999'
      ctx.font = '20px sans-serif'
      ctx.fillText(self.props.date, 70, 460)
      // 昵称
      ctx.fillStyle = '#fff'
      ctx.font = '22px sans-serif'
      const { userData } = self.props.userData
      let nickName = userData.nickname
      ctx.fillText(nickName, 100, 120)
      // 标题
      let titleOptions = {
        color: '#222',
        fontSize: 36,
        align: 'left',
        width: 610,
        line: 2
      }
      drawText(ctx, self.props.title, titleOptions, 70, 536, 610)
      // 文章概要
      let contentOptions = {
        color: '#555',
        fontSize: 28,
        align: 'left',
        width: 610,
        line: 5
      }
      drawText(ctx, self.props.content, contentOptions, 70, 702, 610)


      setTimeout(() => {
        self.saveImage(canvas)
      }, 1000)
    }


    async function drawImageItem(canvas, ctx, src, x, y, wx, wy) {
      let info = await Taro.getImageInfo({ src: src })
      if (info.width && info.height) {
        const img = canvas.createImage()
        img.src = src
        img.onload = () => {
          ctx.drawImage(img, 0, 0, info.width, info.height, x, y, wx, wy)
        }
      } else {
        fail()
      }
    }


    function drawText(ctx, content, option, a, b, c) {
      let row = textWrap(ctx, content, option)
      for (let i = 0; i < row.length; i++) {
        ctx.fillText(row[i], a, b + i * 50, c)
      }
    }


    function fail(err) {
      Taro.showLoading({ title: '网络超时', mask: true })
    }
  }
回答关注问题邀请回答
收藏

1 个回答

登录 后发表内容
问题标签