微信小程序点击保存图片到本机功能

发布时间:2020-08-25 15:40:19 作者:前端_李嘉豪
来源:脚本之家 阅读:148

微信小程序点击保存图片到本机功能

1.首先我们要把想保存的图片绘制在画布上

<view class='container'>
 <canvas style='width:{{canvasWidth}}px; height:{{canvasHeight}}px' class="canvas" id="canvas" canvas-id="canvas" disable-scroll="true">
 </canvas>
 <button bindtap='clickMe'>保存图片</button>
</view>

2.我们在看看看js代码在用wx.canvasToTempFilePath方法会返回一个tempFilePath图片路径

// canvas 全局配置
var context = null;
var rpx
var posterHeight = 0
var posterWidth = 0
var avatarPadding = 0 //距离边界
var avatarRadiu = 0 //头像半径
var textScale = 0 //文字比例
 
//注册页面
Page({
 
 data: {
  img: "../../images/img1.jpg",
  myCanvasWidth: 0,
  myCanvasHeight: 0,
  posterHeight: 0,
 },
 
 onLoad: function (options) {
  var that = this
  var myCanvasWidth = that.data.myCanvasWidth  //为了让图片满铺页面
  var myCanvasHeight = that.data.canvasHeight
  context = wx.createCanvasContext('canvas');
 
  wx.getSystemInfo({
   success: function (res) {
    myCanvasWidth = res.screenWidth
    myCanvasHeight = res.screenHeight
    posterWidth = Math.round(res.screenWidth * 0.68) //计算让画布图片自适应
    posterHeight = Math.round(posterWidth * 1920 / 1080)
    avatarPadding = Math.round(posterWidth * 20 / 375)
    avatarRadiu = Math.round(posterWidth * 25 / 375)
    textScale = Math.round(posterWidth / 375)
    rpx = res.windowWidth / 375;
    that.setData({
     myCanvasWidth: myCanvasWidth,
     myCanvasHeight: myCanvasHeight,
     posterHeight: posterHeight
    })
    context.drawImage(that.data.img, 0, 0, that.data.myCanvasWidth, that.data.myCanvasHeight); //画布绘制图片
    context.draw();
 
   },
  })
 },
 clickMe: function () { //保存图片
  wx.canvasToTempFilePath({
   canvasId: 'canvas',
   fileType: 'jpg',
   success: function (res) {
    console.log(res)
    wx.saveImageToPhotosAlbum({
     filePath: res.tempFilePath,
     success(res) {
      console.log(res)
      wx.hideLoading();
      wx.showToast({
       title: '保存成功',
      });
      // //存入服务器
      // wx.uploadFile({
      //  url: 'a.php', //接口地址
      //  filePath: res.tempFilePath,
      //  name: 'file',
      //  formData: {                 //HTTP 请求中其他额外的 form data 
      //   'user': 'test'
      //  },
      //  success: function (res) {
      //   console.log(res);
 
      //  },
      //  fail: function (res) {
      //   console.log(res);
      //  },
      //  complete: function (res) {
      //  }
      // });
     },
     fail() {
      wx.hideLoading()
     }
    })
   }
  })
 },
})

3,css样式 直接给画布设置高度宽度就可以 图片会铺满屏幕

总结

以上所述是小编给大家介绍的微信小程序点击保存图片到本机功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

推荐阅读:
  1. 微信小程序如何设置保存图片到相册权限
  2. 怎么在微信小程序中实现保存图片到相册功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序 保存 图片

上一篇:Spring Boot JDBC 连接数据库示例

下一篇:怎么命名Python标识符

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》