pdfjs-dist实现pdf预览偶现空白不报错问题解决

javascript 复制代码
const calculateFitScale = (pageWidth, pageHeight) => {
  const canvas = canvasRef.value;
  if (!canvas) return 1;

  const container = document.getElementById("pdf-container");
  if (!container) return 1;

  const containerWidth = container.clientWidth;
  const containerHeight = container.clientHeight;

  if (containerWidth === 0 || containerHeight === 0) {
    return 1;
  }  // 关键代码

  // 计算适应宽度的scale
  const scaleWidth = containerWidth / pageWidth;
  //const scaleHeight = containerHeight / pageHeight;

  // 取平方根使缩放更合理(避免过度缩放)
  return Math.sqrt(scaleWidth);
  // return Math.min(scaleWidth); // 取最小值
};

问题出现情况: 在预览第一张图的时候通常都是成功的,后面的图偶尔会在cavnas中空白渲染,经排查就是初始化渲染的时候,计算适应容器的缩放比例这里出错了,关键解决代码如下:

if (containerWidth === 0 || containerHeight === 0) {

return 1;

}

读取pdf容器的宽高的时候读取到0 ,导致渲染了宽高为0的画布。

相关推荐
小码哥_常27 分钟前
安卓黑科技:实现多平台商品详情页一键跳转APP
前端
killerbasd30 分钟前
还是迷茫 5.3
前端·react.js·前端框架
不会敲代码11 小时前
TCP/IP 与前端性能:从数据包到首次渲染的底层逻辑
前端·tcp/ip
kyriewen2 小时前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·github·openai
AC赳赳老秦2 小时前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen2 小时前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
不会敲代码12 小时前
从零搭建 AI 日记助手:用 Milvus 向量数据库实现语义搜索
javascript·openai
千寻girling2 小时前
《 Git 详细教程 》
前端·后端·面试
threelab3 小时前
Three.js UV 图像变换效果 | 三维可视化 / AI 提示词
javascript·人工智能·uv
之歆3 小时前
DAY08_CSS浮动与行内块布局实战指南(下)
前端·css