微信小程序-生成canvas图片并保存到手机相册

这篇具有很好参考价值的文章主要介绍了微信小程序-生成canvas图片并保存到手机相册。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

wxml页面

<button class="rightbtn bottomBtnCss"  catch:tap="canvasImg">
        <image src='{{imgUrl}}/images/mine/jspj-icon.png' class="restNumImg"></image>
        <text class="btnText">生成图片</text>
      </button>
<!-- 生成图片弹框 -->
<view class="wx-dialog_wrapper "  wx:if="{{isShowCanvas}}" >
  <view class="wx-dialog wx-dialogwidth80">
    <view class="wx-dialog_body">
      <view class="canvasWrap"><canvas type="2d" id='posterCanvas' style="width: 100%;height: 1000rpx;"></canvas></view>
      <button class="rightbtn bottomBtnCss"  catch:tap="saveImg">
        <image src='{{imgUrl}}/images/mine/jspj-icon.png' class="restNumImg"></image>
        <text class="btnText">保存图片</text>
      </button>
    </view>
  </view>
</view>

wxss页面

.wx-dialogwidth80{
  width:80%;
}
#posterCanvas {
  margin: 0 auto;
}
.canvasWrap {
margin: 10px auto;
text-align: center;
}

js代码文章来源地址https://www.toymoban.com/news/detail-692798.html

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl,//线上图片路径
    totalCnt: '',
    isSaveCanvas: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let totalCnt = wx.getStorageSync('totalCnt')
    this.setData({
      totalCnt: totalCnt || '0.00'
    })
  },
  // 重新计算
  restClick() {
    wx.navigateTo({
      url: '../../index'
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  // 关闭
  showVipDialogClose() {
    this.setData({
      isShowCanvas: false
    })
  },
  canvasImg() {
    this.setData({
      isShowCanvas: true
    })
    // wx.showLoading({
    //   title: '海报生成中...',
    // })
    let _this = this
    //选取画板
    const query = wx.createSelectorQuery()
    query.select('#posterCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec(async (res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const dpr = wx.getSystemInfoSync().pixelRatio //手机分辨率 为了使保存到相册的图片清晰
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        console.log('dpr', dpr);
        ctx.clearRect(0, 0, 320, 410); //清空画板
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, 320, 410);
        // 1.背景图
        const image = canvas.createImage();
        image.src = this.data.imgUrl + "/images/carbonEmissionImages/排放总量背景.png";;
        let bgImg = await new Promise((resolve, reject) => {
          image.onload = () => {
            resolve(image)
          }
          image.onerror = (e) => {
            reject(e)
          }
        });
        ctx.drawImage(bgImg, 0, 0, canvas.width, canvas.height);
        // 2.头部文字 在背景图上作画
        // 设置文字样式
        ctx.font = "700 36px sans-serif";
        ctx.fillStyle = "#fff";
        ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
        // 添加文字
        ctx.fillText("我在ESGPRO上测了企业碳排放总量", canvas.width / 2, 200);
        // 3.画中心圆图
        const image1 = canvas.createImage();
        image1.src = this.data.imgUrl + "/images/carbonEmissionImages/tco2背景.png";;
        let bgImgPo = await new Promise((resolve, reject) => {
          image1.onload = () => {
            resolve(image1)
          }
          image1.onerror = (e) => {
            reject(e)
          }
        });
        ctx.drawImage(bgImgPo, 0.5 * (canvas.width - 400), 0.5 * (canvas.height - 800), 400, 400);
        // 4.圆圈内文字 在背景图上作画
        // // 设置文字样式
        ctx.font = "700 36px sans-serif";
        ctx.fillStyle = '#00bf5b'; //文字颜色:默认黑色
        ctx.textAlign = "center"
        ctx.fillText(_this.data.totalCnt, canvas.width / 2, 0.5 * (canvas.height - 400)) //绘制文本
        // 设置文字样式
        ctx.font = "28px sans-serif";
        ctx.fillStyle = "#bdbdbd";
        ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
        // 添加文字
        ctx.fillText('tCO2', canvas.width / 2, 0.5 * (canvas.height - 300));

        // 5.小程序二维码
        let image2 = canvas.createImage();
        // image2.src = this.data.imgUrl + '/images/carbonEmissionImages/COimg.jpg'; // 引入本地图片
        image2.src = '../../images/COimg.jpg'; // 引入本地图片
        image2.onload = function () {
          ctx.drawImage(image2, 0.5 * (canvas.width - 300), 0.5 * (canvas.height + 400), 300, 300);
          // 6.添加文字
          // 设置文字样式
          ctx.font = "24px sans-serif";
          ctx.fillStyle = "#999999";
          ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
          // 添加文字
          ctx.fillText('微信扫码或搜索ESGPRO', canvas.width / 2, 0.5 * (canvas.height + 1100));
          ctx.font = "24px sans-serif";
          ctx.fillStyle = "#999999";
          ctx.textAlign = "center" //居中是以文字设定的x轴( canvas.width/2)为中心点
          // 添加文字
          ctx.fillText('即可免费使用碳排放计算器', canvas.width / 2, 0.5 * (canvas.height + 1200));
        }
      })

  },
  async saveImg() {
    let _this = this;
    const query = wx.createSelectorQuery();
    const canvasObj = await new Promise((resolve, reject) => {
      query.select('#posterCanvas')
        .fields({
          node: true,
          size: true
        })
        .exec(async (res) => {
          resolve(res[0].node);
        })
    });
    wx.canvasToTempFilePath({
      canvas: canvasObj, //现在的写法
      success: (res) => {
        console.log(res);
        _this.setData({
          isShowCanvas: false
        });
        //保存图片
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.hideToast();
            wx.showModal({
              title: '图片保存成功',
              content: '图片成功保存到相册了',
              showCancel: false,
              confirmText: '好哒',
              confirmColor: '#5096cd',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              }
            })
          },
          fail(err) {
            wx.hideToast()
            if (
              err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" ||
              err.errMsg === "saveImageToPhotosAlbum:fail auth deny" ||
              err.errMsg === "saveImageToPhotosAlbum:fail authorize no response"
            ) {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: res => {
                  wx.openSetting({
                    success(res) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败,将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(err) {
                      console.log("fail", err)
                    },
                    complete(res) {
                      console.log("finish", res)
                    }
                  })
                }
              })
            } else if (err.errMsg === "saveImageToPhotosAlbum:fail cancel") {
              wx.showModal({
                title: '提示',
                content: '取消了保存图片,再次点击下载即可保存',
                showCancel: false,
              })
            } else {
              wx.showModal({
                title: '提示',
                content: err.errMsg,
                showCancel: false,
              })
            }
          }
        })
      },
      fail(err) {
        wx.showToast({
          title: '保存失败,稍后再试',
          duration: 2000,
          icon: 'none'
        });
      }
    }, this)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})

到了这里,关于微信小程序-生成canvas图片并保存到手机相册的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序海报插件Painter 2.0(canvas画图)使用并保存图片到相册案例

    Painter通过 json 数据形式,来进行动态渲染并绘制出图片。 Painter 的优势 功能全,支持文本、图片、矩形、qrcode 类型的 view 绘制 布局全,支持多种布局方式,如 align(对齐方式)、rotate(旋转) 支持圆角,其中图片,矩形,和整个画布支持 borderRadius 来设置圆角 支持边框,

    2024年01月20日
    浏览(45)
  • 微信小程序——保存图片到手机相册(代码详解)

    首先我们要知道,如果小程序首次发起授权被拒绝之后,再次点击同一个按钮执行的wx.authorize(...)不会再弹出授权窗口。所以我们需要到引导用户到设置页面进行手动授权。 引导用户到设置页面授权的方式有两种: 第一种: 使用小程序api :wx.openSetting(...)打开设置页面 第二

    2024年02月04日
    浏览(41)
  • 微信小程序实现将图片保存到手机相册

    首先我们需要调用 wx.downloadFile 方法下载文件资源到本地,然后利用 wx.saveImageToPhotosAlbum 方法保存图片到系统相册,需要注意的是这样写很可能会因为没有权限而导致下载不了图片,所以我们最后还需要给接口一个调用失败的回调函数,以此来获取权限,最后这个小功能就实

    2024年02月11日
    浏览(51)
  • 微信小程序canvas生成图片并保存

    需求: 做一个类似下图的功能。图片内容是动态的,用canvas画出来,生成临时图片,再保存。 实现:  其他使用,查看微信开发文档  

    2024年02月13日
    浏览(37)
  • uniapp 微信小程序保存图片到系统相册(包括获取手机相册权限)即拿即用

    1. 代码,即拿即用 2. 介绍使用到的方法 1. uni.getSetting uniapp官网链接: https://uniapp.dcloud.io/api/other/setting.html#getsetting 2. uni.authorize 链接:https://uniapp.dcloud.io/api/other/authorize.html#authorize 3. uni.saveImageToPhotosAlbum 链接: https://uniapp.dcloud.io/api/media/image.html#saveimagetophotosalbum 4. uni.openSe

    2024年02月11日
    浏览(50)
  • 微信小程序canvas type=2d生成海报保存到相册、文字换行溢出显示...、文字删除线、分享面板

    做个简单的生成二维码海报分享, 我做的时候也找简单的方法看能不能实现页面直接截图那种生成图片,原生小程序不支持, 不多介绍下面有全部代码有注释、参数自行替换运行看看,还有需要优化的地方,有问题可以咨询我,我写的已经上线 如图:

    2024年02月11日
    浏览(33)
  • 微信小程序使用canvas绘制海报并保存本地相册

    在做微信小程序的时候,很多都会用到生成海报分享功能,刚好最近项目有这个需求,今天就发出来记录下 首先是使用canvas绘制一张海报,微信小程序的canvas有老版本和新版本我是用的是新版本 代码如下 js部分 我的做法是给canvas隐藏了不看到 ,等canvas绘制完毕后导出的url直接赋给

    2023年04月08日
    浏览(32)
  • uniapp 微信小程序保存图片到系统相册( 获取用户是否开启 授权保存图片到相册。)

    当用户点击拒绝按钮后的截图:   用户点击不授权  则关闭弹窗 单独给用户点击授权后, 跳转到授权页面  开启授权后:

    2024年02月08日
    浏览(41)
  • 在uniapp微信小程序中保存图片到本地相册

    实现在uniapp微信小程序中点击按钮,保存图片到本地相册,具体实现方法: template中 js中 手机运行:  

    2024年02月11日
    浏览(55)
  • 微信小程序 一键保存视频到手机相册功能(视频来源为链接)

    1. 首先第一次要获取用户授权,授权使用相册权限         调用this.onStartDownload()函数获取用户授权 2.拿到视频地址就可以实现下载功能了 3.主要的api:         wx.downloadFile()           wx.getFileSystemManager()         wx.saveVideoToPhotosAlbum() 视频链接为 http://xxxxxx.mp4 形

    2024年02月11日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包