wx.canvasToTempFilePath 输出的图片一直以 canvas 初始样式大小为基准
发布于 5 年前 作者 tao12 11516 次浏览 来自 问答
<canvas type="2d" id="canvas"></canvas>
<image src="{{tempFilePath}}" mode="widthFix" />
canvas {
  width: 200px;
  height: 250px;
  outline: 2px solid red;
}

image {
  width: 100px;
  outline: 2px solid blue;
}
wx
      .createSelectorQuery()
      .select('#canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const img = canvas.createImage();
        img.onload = () => {
          canvas.width = 400;
          canvas.height = 500;
          canvas.getContext('2d').drawImage(img, 0, 0);
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 50,
            height: 50,
            canvas,
            success: res => this.setData({ tempFilePath: res.tempFilePath }),
          });
        };
        img.src = 'pic.png'; // 400x500 的网格图
      });

上面的代码会绘制出(蓝色部分正确)

如果 canvas 默认大小改为 100x100,在 canvasToTempFilePath 之前才设置为 200x250,同样的参数 wx.canvasToTempFilePath 输出的是以 canvas 初始大小绘制的内容(蓝色区域应该只有一格,而不是四格)

<canvas type="2d" id="canvas" style="width:{{w}};height:{{h}}"></canvas>
<image src="{{tempFilePath}}" mode="widthFix" />

canvas {
  width: 100px;
  height: 100px;
  outline: 2px solid red;
}

image {
  width: 100px;
  outline: 2px solid blue;
}

Page({
  data: {
    tempFilePath: '',
    w: '',
    h: '',
  },
  onReady() {
    wx
      .createSelectorQuery()
      .select('#canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const img = canvas.createImage();
        img.onload = () => {
          canvas.width = 400;
          canvas.height = 500;
          canvas.getContext('2d').drawImage(img, 0, 0);
          this.setData({
            w: '200px',
            h: '250px',
          }, () => {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 50,
              height: 50,
              canvas,
              success: res => this.setData({ tempFilePath: res.tempFilePath }),
            });
          });
        };
        img.src = 'pic.png';
      });
  },
});
回到顶部