收藏
回答

微信小程序PC端加载图片获取不了尺寸,手机端是好的,要怎么做兼容处理?

// 在canvas绘图时,需要获取图片尺寸,再完整绘制图片,再手机端一起OK,
// 但在小程序PC版中遇到了如下注释中的问题,这应该时小程序的BUG,想知道如何解决
export const createCanvasByImage = (src, canvasId) => {
  return new Promise(resolve => {
    Taro.createSelectorQuery().select(`#${canvasId}`)
      .fields({ node: true, size: true }).exec(res => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const img = canvas.createImage();
        img.src = src;
        img.onload = async (e) => {
          if (img.width) {
                  // 手机端中能正常获取img或e.path[0]
            canvas.width = img.width;
            canvas.height = img.height;
          } else {
            // PC版小程序中img为空对象{},即获取img.width为undefined
          }
          ctx.drawImage(img, 0, 0);
          resolve({ canvas, res, ctx });
        }
      });
  })
}
回答关注问题邀请回答
收藏

1 个回答

登录 后发表内容