Taro 小程序分享二维码图片

27 篇文章 1 订阅
4 篇文章 0 订阅

定义分享按钮和canvas画布

// 分享按钮
<View className='job-bottom-share share' onClick={() => this.handleOpenShare()}>
  <View>
    <Text className='iconfont icon-share-ic share-img'></Text>
  </View>
  <Text>分享</Text>
</View>
// canvas画布弹窗
{/* canvas */}
<View className={`canvas-index ${canvasVisible ? '' : 'cavas-hidden'}`}>
  {
    canvasType === 2 ?
      <View className='canvas-wrap'>
        <View className='canvas-top at-row at-row__justify--between at-row__align--center'>
          <Text>推荐好友</Text>
          <Image src={closeIcon} className='close-icon' onClick={() => handleCtrCanvasVisible(canvasVisible, -1)} />
        </View>
        <Canvas
          id='cardCanvas'
          canvas-id='cardCanvas'
          className='card-canvas'
          // style='width: 320px; height: 450px'
          type='2d'
          canvasId='cardCanvas' >
        </Canvas>
        <Button onClick={this.saveCard} className='btn-save' type='primary' size='mini'>保存到相册</Button>
      </View> : ''
  }
  {
    canvasType === 1 ?
      <View className='canvas-wrap share-wrap'>
        <View className='canvas-top at-row at-row__justify--between at-row__align--center'>
          <Text>推荐好友</Text>
          <Image src={closeIcon} className='close-icon' onClick={() => handleCtrCanvasVisible(canvasVisible, -1)} />
        </View>
        <View className='wecaht-content at-row at-row__justify--between at-row__align--center'>
          <Button openType='share' className='share-friend' onClick={() => this.handleShare()}>
            <Image src={wechatIcon} className='wechat-icon' />
            <View className='share-txt'>转发给好友或群聊</View>
          </Button>
          <View onClick={() => handleCtrCanvasVisible(false, 2)}>
            <Image src={friendIcon} className='wechat-icon' />
            <View className='share-txt'>生成朋友圈图片</View>
          </View>
        </View>
      </View> : ''
  }
  {
    canvasType === 3 ?
      <View className='canvas-wrap share-wrap'>
        <View className='canvas-top at-row at-row__justify--end at-row__align--end'>
          <Image src={closeIcon} className='close-icon' onClick={() => handleCtrCanvasVisible(canvasVisible, -1)} />
        </View>
        <View className='wecaht-content new-pad at-row at-row__justify--center at-row__align--center'>
          <View>
            <Image src={saveOkIcon} className='save-icon' />
            <View className='save-ok share-txt'>图片已保存到系统相册</View>
          </View>
        </View>
        <View className='close-btn' size='mini' onClick={() => handleCtrCanvasVisible(canvasVisible, -1)} >我知道了</View>
      </View> : ''
  }
</View>

在这里插入图片描述

打开分享的弹窗

// 点击触发打开分享的弹窗
handleOpenShare() {
    // this.drawImage()
    const { handleCtrCanvasVisible, canvasVisible } = this.props
    // console.log({canvasVisible})
    handleCtrCanvasVisible(canvasVisible, 1)
    let _this = this
    if (canvasVisible) {
      // 创建一个选择器对象
      const query = Taro.createSelectorQuery()
      // 选择当前页面下第一个 #canvas
      // 返回 NodesRef 用于获取 WXML 节点信息的对象
      query.select('#cardCanvas').fields({ node: true, size: true })
        .exec((res) => {
          _this.drawImage(res)

        })
    }
  }
  
// 这个时候可能会取不到canvas的id,所以要在componentDidUpdate的时候
 componentDidUpdate() {
    const { canvasVisible, canvasType } = this.props
    let _this = this
    // 创建一个选择器对象
    const query = Taro.createSelectorQuery()
    // 有#cardCanvas再调用this.drawImage
    if (canvasVisible && canvasType === 2 && query.select('#cardCanvas')) {
      // 选择当前页面下第一个 #canvas
      // 返回 NodesRef 用于获取 WXML 节点信息的对象
      query.select('#cardCanvas').fields({ node: true, size: true })
        .exec((res) => {
          _this.drawImage(res)

        })
    }
  }

Canvas绘制方法


/**
   * drawImage() 定义绘制图片的方法
   */
  drawImage(res) {
    // console.log({ res })
    const { jobdetail = {}, userInfo } = this.props
    const { name, RecruiType = '', CompanyName = '', Salary = '', City = '', Department = '', RecruitNum, modifiedTime, JobDescription, PositionDes, PositionRequire, elink, id } = jobdetail
    const salary = Salary ? JSON.parse(Salary).name : '';
    // const { jobId } = this.$router.params
    const { jobId } = this.state
    // console.log('drawImage jobId', this.$router.params.jobId, jobId)
    
    const canvas = res[0].node
    this.canvas = canvas
    // console.log({canvas})
    // Canvas 的绘图上下文
    const ctx = canvas.getContext('2d')

    // 设备像素比
    // 这里根据像素比来设置 canvas 大小
    const dpr = Taro.getSystemInfoSync().pixelRatio
    canvas.width = 380 * dpr
    canvas.height = 675 * dpr
    // console.log({ ctx })
    ctx.scale(dpr, dpr)
    ctx.fillStyle = '#5B9AFF'
    ctx.fillRect(0, 0, 380, 675)
    // ctx.fillRect(0, 0, 100, 100)
    // 绘制文本
    // ctx.setFontSize(36)
    ctx.font = `normal 300 36px PingFangSC-Light,PingFang`
    ctx.fillStyle = '#fff'
    ctx.fillText('热招职位', 113, 60)
    // ctx.textAlign='center'

    // 绘制矩形
    ctx.fillStyle = "#fff";
    ctx.fillRect(24, 132, 331, 508);
    // ctx.textAlign='center'
    // ctx.stroke();
    // 绘制文本
    ctx.font = `normal 500 24px PingFangSC-Light,PingFang`
    ctx.fillStyle = '#313753'
    ctx.fillText(name, 130, 193)
    // ctx.textAlign='center'

    // 绘制文本
    ctx.font = `normal 500 24px PingFangSC-Light,PingFang`
    ctx.fillStyle = '#F4A25A'
    ctx.fillText(`${salary || ''} ${City ? '|' : ''} ${City || ''}`, 105, 243)
    // ctx.textAlign='center'
    // 绘制文本
    ctx.font = `normal 400 16px PingFangSC-Light,PingFang`
    ctx.fillStyle = '#313753'
    ctx.fillText(CompanyName || '', 158, 292)
    // ctx.textAlign='center'
    const tenantId = Taro.getStorageSync('tenantId') // 租户id
    const referrer = userInfo.passid // 推荐人id,谁分享谁就是推荐人
    // 获取图片信息
    Taro.getImageInfo({
      src: `${fly.config.baseURL}/open_api/getQRcode?jobId=${jobId}&tenantId=${tenantId}&referrer=${referrer}`,
      success: resImg => {
        // 创建一个图片对象
        const img = canvas.createImage();

        img.src = resImg.path
        img.onload = () => {
          // 绘制图像到画布
          ctx.drawImage(img, 94, 338, 191, 191)
        }
      },
      fail(fail) {
        console.log(fail)
      }
    })

    // 绘制文本
    ctx.font = `normal 400 14px PingFangSC-Light,PingFang`
    ctx.fillStyle = '#313753'
    ctx.fillText('长按查看职位详情', 133, 580)
    ctx.textAlign = 'center'


  }

  /**
  * saveCard() 保存图片到本地
  */
  saveCard() {
    const { handleCtrCanvasVisible } = this.props
    // 将Canvas图片内容导出指定大小的图片
    Taro.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 750,
      height: 1334,
      destWidth: 750,
      destHeight: 1334,
      canvasId: '#cardCanvas',
      canvas: this.canvas,
      success(res) {
        Taro.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(saveRes) {
            console.log(saveRes, 'saveRes')
            handleCtrCanvasVisible(false, 3) // 关闭canvas弹窗
            // Taro.showModal({
            //   title: '图片保存成功',
            //   content: '图片成功保存到相册了,快去发朋友圈吧~',
            //   showCancel: false,
            //   confirmText: '确认'
            // })
          }
        })
      },
      fail(fail) {
        console.log(fail)
        Taro.showModal({
          title: '图片保存失败',
          content: '请重新尝试!',
          showCancel: false,
          confirmText: '确认'
        })
      }
    })
  }

在这里插入图片描述

公众号

欢迎大家关注我的公众号: 石马上coding,一起成长
石马上coding

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值