欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-05-12 09:09:57|栏目:JavaScript代码|点击:

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样式 直接给画布设置高度宽度就可以 图片会铺满屏幕

总结

上一篇:JS获取select的value和text值的简单实例

栏    目:JavaScript代码

下一篇:微信小程序搜索组件wxSearch实例详解

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

本文地址:http://www.codeinn.net/misctech/119651.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有