You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-pdf Canvas绑定click事件绘制矩形位置偏移问题求解

问题根源

这个偏差是因为Canvas存在两套独立尺寸导致的:

  • Canvas元素本身的width/height属性:对应画布实际像素分辨率,react-pdf会根据PDF原生分辨率、设备像素比、当前页面缩放倍数动态设置,通常远大于视觉可见尺寸
  • Canvas的CSS渲染尺寸:就是getBoundingClientRect返回的宽高,是用户肉眼看到的画布显示大小
    你代码中直接用点击得到的CSS坐标绘制,没有做比例换算,就会出现大幅偏移。
修复方案

计算两个维度的缩放比例,把CSS坐标映射为画布实际像素坐标后再绘制,修改后代码如下:

const cursor_pdf = document.getElementsByClassName('react-pdf__Page__canvas')[0];
cursor_pdf?.addEventListener('click', (e) => {
    const rect = cursor_pdf.getBoundingClientRect();
    // 计算坐标缩放比例
    const scaleX = cursor_pdf.width / rect.width;
    const scaleY = cursor_pdf.height / rect.height;

    // 坐标换算到画布实际像素坐标
    const x = (e.clientX - rect.left) * scaleX;
    const y = (e.clientY - rect.top) * scaleY;

    const marker = cursor_pdf.getContext("2d");
    marker.beginPath();
    marker.lineWidth = "3";
    marker.strokeStyle = "red";
    // 如果需要点击点在矩形中心,可调整为 marker.rect(x - 25, y - 25, 50, 50);
    marker.rect(x, y, 50, 50);
    marker.stroke();
});
注意事项
  • 若你的项目支持PDF缩放操作,每次缩放后上述scaleX/scaleY会自动变化,不需要额外修改代码,动态计算即可适配
  • 若存在多页PDF,需要为每一页的canvas单独绑定事件监听

内容的提问来源于stack exchange,提问作者mne_web_dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:06:03