收藏
回答

canvasToTempFilePath图片变形?

我用canvas载入图片:

wx.createSelectorQuery().select('#myCanvas').fields({ node: true, size: true }).exec((res)=>{
      const canvas = res[0].node
      that.canvas = canvas;
      that.context = canvas.getContext('2d')
      canvas.width = res[0].width * app.globalData.pixelRatio
      canvas.height = res[0].height * app.globalData.pixelRatio
      const img = canvas.createImage();
      img.src = that.data.url;
      img.onload = () => {
        //计算图片和canvas的宽高比,对图片进行保持比例缩放。图片可正常按比例载入
        that.context.drawImage(img, 0, 0, that.data.scaledWidth/**计算后的图片宽**/, that.data.scaledHeight/**计算后的图片高**/);
      }
}
confirmTap: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存图片',
    })
    setTimeout(() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: that.data.scaledWidth,
          height: that.data.scaledHeight,
          destWidth: that.data.scaledWidth * app.globalData.pixelRatio,    /**app.globalData.pixelRatio为像素比**/
          destHeight: that.data.scaledHeight * app.globalData.pixelRatio,
          // width: 10,
          // height: 10,
          // destHeight: 300,
          // destWidth: 300,
          fileType: 'jpg',
          canvas: this.canvas,
          success: function (res) {
            console.log(res);
            var tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success:function(res){
                wx.hideLoading()
              }
            })
          }
        })
      }, 1500);
}

但实际保存的图片是整个canvas的宽高,但被缩放成that.data.scaledWidth * app.globalData.pixelRatio和that.data.scaledHeight * app.globalData.pixelRatio

加载时的图片

保存的图片



回答关注问题邀请回答
收藏

2 个回答

  • 余温无痕
    余温无痕
    2022-01-22

    有没有试过destWidth不乘像素比,直接乘倍数,看是不是正常的?我一般生成海报,保存到相册等等都是乘以倍数,修改成下面的试试

    canvas.width = res[0].width
    canvas.height = res[0].height
    
    destWidth: that.data.scaledWidth * 3,    /**app.globalData.pixelRatio为像素比**/
    destHeight: that.data.scaledHeight * 3,
    


    2022-01-22
    有用
    回复 6
    • 邵
      发表于移动端
      2022-01-22
      一个手机的像素比不就是固定值吗,我先试试看吧
      2022-01-22
      回复
    • 邵
      2022-01-22
      经测试不行,还是偶尔正常,大部分时候变形
      2022-01-22
      回复
    • 余温无痕
      余温无痕
      2022-01-22回复
      这两个scaledWidth和scaledHeight 你是怎么计算的?贴下代码,有没有打印下计算后的宽度和高度?
      2022-01-22
      回复
    • 邵
      2022-01-22回复余温无痕
      问题解决了。是这样,我在wxml文件里在canvas外面包了一个view,设置了width和height,canvas的width和height我是在css文件里设置为100%。
      然后获取scaledWidth和scaledHeight的代码:
      2022-01-22
      回复
    • 邵
      2022-01-22
      图中res[0].height和res[0].width之前用的是外层view的高和宽,就会变形。改了之后正常了。但不知道为什么。照理canvas的高和宽和外层view的是一样的
      2022-01-22
      回复
    查看更多(1)
  • 邵
    2022-01-21

    奇怪的是偶尔会正常

    2022-01-21
    有用
    回复
登录 后发表内容