Taro 微信小程序 实现海报分享

3,450 阅读2分钟

由于小程序的分享只能分享给好友,不能通过其他的渠道去分享,所以就有了海报的这种需求

思路

  • 利用 canvas 将海报画出来
  • 将画出来的海报转换成图片
  • 将图片保存至本地相册

引入 Canvas

指定 type='2d' 来提升性能

import { Canvas } from '@tarojs/components'

<Canvas id='canvas' className='canvas' type='2d' />

获取 Canvas 节点

    // 创建一个选择器对象
    const query = Taro.createSelectorQuery()
    // 选择当前页面下第一个 #canvas 
    // 返回 NodesRef 用于获取 WXML 节点信息的对象
    query.select('#canvas')
      // 获取节点的相关信息。需要获取的字段在fields中指定。返回值是 nodesRef 对应的 selectorQuery
      .fields({ node: true, size: true })
      // 执行所有的请求。请求结果按请求次序构成数组,在callback的第一个参数中返回
      .exec(this.draw.bind(this))

创建 Canvas 实例

  draw(res: NodesRef) {
    // Canvas 实例
    const canvas = res[0].node
    this.canvas = canvas
    // Canvas 的绘图上下文
    const ctx = canvas.getContext('2d')

    ...
}

开始绘制

draw(res: NodesRef) {
    // Canvas 实例
    const canvas = res[0].node
    this.canvas = canvas
    // Canvas 的绘图上下文
    const ctx = canvas.getContext('2d')

    // 设备像素比
    // 这里根据像素比来设置 canvas 大小
    const dpr = Taro.getSystemInfoSync().pixelRatio
    canvas.width = res[0].width * dpr
    canvas.height = res[0].height * dpr
    ctx.scale(dpr, dpr)

   // 解决下载来的图片是黑色背景的问题
    ctx.fillStyle = '#ffffff'
    ctx.fillRect(0, 0, res[0].width, res[0].height)

    // 获取图片信息
    Taro.getImageInfo({
      src: '../../images/banner_01.png',
      success: resImg => {
        // 创建一个图片对象
        const img = canvas.createImage();

        img.src = '../../' + resImg.path
        img.onload = () => {
          // 绘制图像到画布
          ctx.drawImage(img, 0, 0, 300, 150)
        }


      },
      fail(fail) {
        console.log(fail)
      }
    })

    // 绘制文本
    ctx.font = '18px Microsoft YaiHei'
    ctx.fillStyle = 'black'
    ctx.fillText('英语直播', 20, 180)

    // 同上面的功能
    const img = canvas.createImage();

    img.src = '../../images/shera.png'
    img.onload = () => {
      ctx.drawImage(img, 20, 200, 70, 70)
    }

    // 绘制文本
    ctx.font = '14px Microsoft YaiHei'
    ctx.fillStyle = 'blue'
    ctx.fillText('@Owen', 120, 200)

    // 绘制文本
    ctx.font = '12px sans-serif'
    ctx.fillStyle = 'black'
    ctx.fillText('给你推荐一堂好课', 120, 220)

    // 绘制文本
    ctx.font = '12px sans-serif'
    ctx.fillStyle = 'black'
    ctx.fillText('长按识别小程序查看课程', 120, 240)

    // 绘制文本
    ctx.font = '10px sans-serif'
    ctx.fillStyle = 'gary'
    ctx.fillText('来自:奋翔升学服务中心', 120, 260)
  }

注意点: ctx.setFillStyle 需要用 ctx.fillStyle 代替 ctx.setFontSize 需要用 ctx.font 代替 在绘制网络图片的时候需要先调用 Taro.getImageInfo 获得图片信息,创建图片对象之后才能进行绘制

保存到相册

    Taro.canvasToTempFilePath({
      canvasId: '#canvas',
      canvas: this.canvas,
      success(res) {
        Taro.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(saveRes) {
            console.log(saveRes, 'saveRes')
          }
        })
      },
      fail(fail) {
        console.log(fail)
      }
    })

【笔记不易,如对您有帮助,请点赞,谢谢】