HTML5中无法直接通过PointerEvent获取手写笔压力值,因pressure属性已被弃用;实际需依赖Chrome/Edge非标准支持、getCoalescedEvents()或降级方案如速度/倾斜角估算。

HTML5 中无法直接通过 PointerEvent 获取手写笔的压力值(如 `pressure`),因为该属性在标准中已被弃用且多数浏览器不支持。实际可用的压力感应需依赖 getCoalescedEvents() 或更可靠的 pointermove 事件配合 inputSource 类型判断,再结合 PressureEvent(实验性)或 Web API 扩展(如 Chrome 的 PointerEvent.pressure 非标准但可用)。
确认设备与浏览器支持压力数据
并非所有触控屏+手写笔组合都上报压力。需先验证:
- 使用 Chrome(v111+)或 Edge(Chromium 内核)——目前仅它们在部分设备上保留非标准
PointerEvent.pressure(范围 0.0–1.0) - 检查
event.inputSource === 'pen',排除鼠标/触摸干扰 - 在
pointerdown时打印事件对象,观察是否存在pressure或tiltX/tiltY字段
用 pointermove + pressure 动态控制画笔粗细
在 Canvas 绘图中,监听 pointermove 并根据压力映射线宽:
const canvas = document.getElementById('drawCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
<p>canvas.addEventListener('pointerdown', (e) => {
if (e.inputSource === 'pen') {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
});</p><p>canvas.addEventListener('pointermove', (e) => {
if (!isDrawing || e.inputSource !== 'pen') return;</p><p>// ✅ Chrome/Edge:使用非标准但广泛可用的 pressure 属性
const pressure = e.pressure ?? 0.5; // fallback 到中等压力
const lineWidth = Math.max(1, Math.min(20, pressure * 18 + 2)); // 映射为 2–20px</p><p>ctx.lineWidth = lineWidth;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
});</p><p>canvas.addEventListener('pointerup', () => {
isDrawing = false;
});
提升精度:使用 getCoalescedEvents() 补偿采样延迟
原生 pointermove 在高速书写时可能丢帧。调用 e.getCoalescedEvents() 可获取同一帧内多个高精度采样点(含各自 pressure):
文章转信息图。将文章/笔记转化为手机可读的 HTML 信息图,自动匹配视觉风格。触发场景:文章转图、笔记转图、信息图、转小红书图、做张图、可视化这篇文章、文生图。
立即学习“前端免费学习笔记(深入)”;
- 仅在支持的浏览器中生效(Chrome ≥ 95,Edge ≥ 95)
- 每个 coalesced event 都带独立
pressure,适合绘制平滑变径笔迹 - 需在
pointermove中遍历并逐点绘制(避免简单取平均)
示例节选:
canvas.addEventListener('pointermove', (e) => {
if (!isDrawing || e.inputSource !== 'pen') return;
<p>const events = e.getCoalescedEvents();
for (const evt of events) {
const p = evt.pressure ?? 0.5;
const w = Math.max(1, p * 18 + 2);</p><pre class="brush:php;toolbar:false;">ctx.lineWidth = w;
ctx.lineTo(evt.offsetX, evt.offsetY);
ctx.stroke();
ctx.beginPath(); // 新路径起点
ctx.moveTo(evt.offsetX, evt.offsetY);} });
降级方案:无 pressure 时用速度或倾斜角估算
当 e.pressure 为 undefined 或恒为 0.5(常见于 Windows Ink 或旧驱动),可退而求其次:
- 用连续两次
pointermove的位移差估算速度 → 速度快则线细(模拟“提笔”) - 读取
e.tiltX/e.tiltY(如有)→ 倾斜越大,模拟侧锋,适当加粗 - 或固定为 2–3 档可切换的预设粗细,由用户手动调节(UI 提供 slider)


















