uni-app canvas 生成的图片无法分享到朋友圈

uni-app canvas 生成的图片无法分享到朋友圈

开发环境 版本号 项目创建方式
Windows 7 HBuilderX

产品分类:

  • uniapp/App

PC开发环境操作系统:

  • Windows

HBuilderX类型:

  • 正式

HBuilderX版本号:

  • 3.1.2

手机系统:

  • Android

手机系统版本号:

  • Android 11

手机厂商:

  • vivo

手机机型:

  • iqoo V1824A

页面类型:

  • vue

打包方式:

  • 云端

App下载地址或H5网址:

示例代码:

<markdown> var that=this; var canvas = uni.createCanvasContext('graceCanvas'); canvas.fillStyle = 'rgb(255,255,255)'; canvas.fillRect(0, 0, 550, 950); var newName = _self.nickname.substr(0, 17); if (_self.nickname.length > 25) newName += '...'; canvas.font = '18px Arial'; canvas.fillStyle = '#000000'; canvas.fillText(newName, 15, 300); canvas.font = '14px Arial'; canvas.fillStyle = '#999999'; canvas.fillText(_self.title, 15, 325); canvas.drawImage(_self.logo,15,450,63,9.5); uni.downloadFile({ url: _self.headimgurl, //仅为示例,并非真实的资源 success: (res) => { if (res.statusCode === 200) { canvas.drawImage(res.tempFilePath, 0, 0,275, 275); canvas.draw(true,(res)=>{ uni.downloadFile({ url: _self.url, //仅为示例,并非真实的资源 success: (res) =>{ canvas.drawImage(res.tempFilePath, 185, 385, 80, 80); canvas.draw(true,(res)=>{ uni.canvasToTempFilePath({ canvasId: 'graceCanvas', success: function(res) { that.imgSrc=res.tempFilePath; uni.hideLoading(); } }) }); }, }) }); } } }); uni.share({ provider: "weixin", scene: "WXSenceTimeline", type: 2, imageUrl: this.imgSrc, success: function(res) { console.log("success:" + JSON.stringify(res)); this.fxshow = false; }, fail: function(err) { console.log("fail:" + JSON.stringify(err)); } }); </markdown>

更多关于uni-app canvas 生成的图片无法分享到朋友圈的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app canvas 生成的图片无法分享到朋友圈的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中,canvas生成图片后分享到朋友圈失败是常见问题,主要原因是图片路径处理和异步时序控制不当。

从你的代码看,存在以下关键问题:

  1. 异步时序错误uni.canvasToTempFilePath是异步操作,但你在其success回调外部直接调用了uni.share,此时this.imgSrc尚未赋值成功。

  2. 图片路径格式:canvas生成的临时路径在分享时可能需要转换为base64或网络路径,微信分享对本地临时路径支持有限。

建议修改方案:

// 在canvasToTempFilePath的success回调中执行分享
uni.canvasToTempFilePath({
  canvasId: 'graceCanvas',
  success: (res) => {
    this.imgSrc = res.tempFilePath;
    uni.hideLoading();
    
    // 在此处调用分享
    uni.share({
      provider: "weixin",
      scene: "WXSenceTimeline",
      type: 2,
      imageUrl: this.imgSrc,
      success: (res) => {
        console.log("success:" + JSON.stringify(res));
        this.fxshow = false;
      },
      fail: (err) => {
        console.log("fail:" + JSON.stringify(err));
      }
    });
  }
});
  1. Android路径兼容性:Android 11对文件访问权限更严格,确保临时文件路径可被微信客户端读取。如仍失败,可尝试将图片保存到相册后分享:
// 保存到相册获取永久路径
uni.saveImageToPhotosAlbum({
  filePath: this.imgSrc,
  success: () => {
    // 使用相册路径分享
  }
});
回到顶部