uni-app微信小程序canvas中使用canvasToTempFilePath在手机上导出图片尺寸与实际不符

文章讨论了微信小程序中图片尺寸不一致的问题,通过使用canvas并结合设备像素比(pixelRatio)进行调整,确保在不同设备上下载图片尺寸的一致性。作者提供了获取设备信息、调整canvas大小以及保存图片到本地的代码示例。

问题描述:比如图片的尺寸是1125*2001像素,这样用微信开发者工具下载下来的图片尺寸是1125*2001像素,用不同的手机去操作,下载出来的图片尺寸都不一样,和原图片尺寸差距很大。

解决方案:canvas写入的时候是按照当前设备像素比(pixelRatio)进行设置的,像素比pixelRatio=物理像素/设备独立像素(dips)

像素比pixelRatio=物理像素/设备独立像素(dips)

ctx.drawImage(图片对象, 图像裁剪的x位置, 图像裁剪的y位置, 裁剪的宽度, 裁剪的高度, x位置, y位置, 宽度, 高度

我这台机器的设备像素比=3,分辨率是:1920*1080 以x轴为例,这里的物理像素=1920,得出设备独立像素=1920/3=640,而canvas这里设置的大小是设备独立像素,所以576的物理像素对应到设备独立像素就是=576/3=192,

微信小程序提供了wx.getSystemInfo获取设备信息,其中pixelRatio就是设备像素比.

canvas写入的时候是按照当前设备像素比(pixelRatio)进行设置的

<button class="btn-link save-link" plain="true" @click="getCanvas">
保存图片
</button>    
<!--  canvas保存图片  -->
<canvas class="share-canvas" canvas-id="canvas" :style="canvasStyle"></canvas>
  data() {
    return {
      posterImg: {
        url: 'https://picsum.photos/1125/2001?random=1',
        width: '1125rpx',
        height: '2001rpx'
      }
    }
  },
computed: {
    canvasStyle() {
      return `width: ${this.posterImg.width}px; height:${this.posterImg.height}px;`
    }
},
methods: {
    getCanvas() {
      uni.showLoading({
        title: '保存中' // 加载转圈显示
      })
      const ctx = uni.createCanvasContext('canvas', this)
      const that = this
      // 获取背景海报详细信息
      uni.getImageInfo({
        src: that.swiper2List[that.current].image,
        success: function(res) {
          // 微信小程序提供了wx.getSystemInfo获取设备信息,其中pixelRatio就是设备像素比
          wx.getSystemInfo({
            success: function(data) {
              // canvas写入的时候是按照当前设备像素比(pixelRatio)进行设置的
              const pixelRatio = data.pixelRatio
              that.posterImg.width = res.width / pixelRatio
              that.posterImg.height = res.height / pixelRatio
              // 绘制背景海报
              ctx.drawImage(res.path, 0, 0, that.posterImg.width, that.posterImg.height)
              that.saveCanvas()
            }
          })
        }
      })
    },
    // 保存canvas为图片
    saveCanvas() {
      const _this = this
      setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: 'canvas',
          quality: 1,
          success(result) {
            // 保存在本地
            uni.saveImageToPhotosAlbum({
              filePath: result.tempFilePath,
              success: function() {
                uni.hideLoading()
                uni.showToast({
                  title: '保存成功',
                  icon: 'success',
                  duration: 2000
                })
                console.log('save success')
              },
              fail: () => {
                uni.hideLoading()
                _this.setData({
                  flag: false
                })
              }
            })
          },
          fail: () => {
            uni.hideLoading()
            // 重复请求一次
            _this.saveCanvas()
          }
        })
      }, 200)
    }
  }
虽然提供的引用内容未直接涉及在uni-app微信小程序使用canvas实现图片缩放时限制最大和最小比例的方法,但可以从原理角度说明实现思路。 在uni-app使用canvas实现图片缩放时,通常会借助触摸事件(如`touchstart`、`touchmove`、`touchend`)来检测用户的缩放操作。可以通过`scale`变量来记录当前的缩放比例,在每次缩放操作时,对`scale`的值进行检查和限制。 以下是一个简单的示例代码: ```javascript <template> <view> <canvas canvas-id="myCanvas" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd"></canvas> </view> </template> <script> export default { data() { return { ctx: null, startDistance: 0, currentScale: 1, minScale: 0.5, maxScale: 2 }; }, onReady() { this.ctx = uni.createCanvasContext('myCanvas', this); // 绘制初始图片 this.ctx.drawImage('yourImagePath', 0, 0, 200, 200); this.ctx.draw(); }, methods: { onTouchStart(e) { if (e.touches.length === 2) { const dx = e.touches[1].clientX - e.touches[0].clientX; const dy = e.touches[1].clientY - e.touches[0].clientY; this.startDistance = Math.sqrt(dx * dx + dy * dy); } }, onTouchMove(e) { if (e.touches.length === 2) { const dx = e.touches[1].clientX - e.touches[0].clientX; const dy = e.touches[1].clientY - e.touches[0].clientY; const currentDistance = Math.sqrt(dx * dx + dy * dy); const scaleChange = currentDistance / this.startDistance; const newScale = this.currentScale * scaleChange; // 限制缩放比例 if (newScale < this.minScale) { this.currentScale = this.minScale; } else if (newScale > this.maxScale) { this.currentScale = this.maxScale; } else { this.currentScale = newScale; } // 清空画布 this.ctx.clearRect(0, 0, 200, 200); // 重新绘制图片并应用缩放 this.ctx.scale(this.currentScale, this.currentScale); this.ctx.drawImage('yourImagePath', 0, 0, 200, 200); this.ctx.draw(); this.startDistance = currentDistance; } }, onTouchEnd() { // 触摸结束处理 } } }; </script> ``` 在上述代码中,`minScale`和`maxScale`分别定义了最小和最大缩放比例。在`onTouchMove`方法中,计算新的缩放比例`newScale`,并检查是否超出了最大和最小比例的范围,如果超出则将`currentScale`设置为对应的边界值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值