收藏
回答

wx.canvasToTempFilePath 输出的图片大小尺寸变形

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug wx.canvasToTempFilePath 工具 8.0.2 2.16.1

原始图片是 400x500 的网格图,就是红色框内的样子。

红色框内是在 canvas 上绘制的等比例原图,蓝色框内是通过 wx.canvasToTempFilePath 输出的图片分片,但是生成的图片比例大小明显和 canvas 不一致,是哪里的问题?

<canvas type="2d" id="canvas" style="width:{{containerW}};height:{{containerH}}"></canvas>

<view class="grid" style="width:{{containerW}};height:{{containerH}}">
  <view class="cell" wx:for="{{pieces}}" style="width:{{item.width}};height:{{item.height}}">
    <image src="{{item.src}}" />
  </view>
</view>


Page({
  data: {
    containerW: '',
    containerH: '',
    pieces: [],
  },
  onReady() {
    const cols = 4;
    const rows = 5;
    const containerW = wx.getSystemInfoSync().windowWidth * .5;
    const containerH = containerW * rows / cols;

    this.setData({
      containerW: `${containerW}px`,
      containerH: `${containerH}px`,
    });

    wx
      .createSelectorQuery()
      .select('#canvas')
      .fields({ node: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const img = canvas.createImage();

        canvas.width = 400;
        canvas.height = 500;

        img.onload = () => {
          ctx.drawImage(img, 0, 0);

          const promises = [];
          const cellW = containerW / cols;
          const cellH = containerH / rows;

          for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
              promises.push(new Promise((resolve, reject) => {
                wx.canvasToTempFilePath({
                  x: col * cellW,
                  y: row * cellH,
                  width: cellW,
                  height: cellH,
                  canvas,
                  fileType: 'jpg',
                  success: res => resolve({
                    width: `${cellW}px`,
                    height: `${cellH}px`,
                    src: res.tempFilePath,
                  }),
                  fail: res => reject(new Error(res.errMsg)),
                });
              }));
            }
          }

          Promise.all(promises).then(pieces => this.setData({ pieces }));
        };

        img.src = 'pic.png';
      });
  },
});


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

2 个回答

  • 邵
    2022-01-21

    很坑!!

    2022-01-21
    有用
    回复
  • 小影
    小影
    2021-05-07

    没人遇到这问题吗?

    2021-05-07
    有用
    回复
登录 后发表内容