PointerEvent:persistentDeviceId 属性
persistentDeviceId 是 PointerEvent 接口的一个只读属性,它是生成 PointerEvent 的指向设备的唯一标识符。这提供了一种安全可靠的方式来识别同时与屏幕交互的多个指向设备(例如手写笔)。
persistentDeviceId 在浏览会话的生命周期内保持不变。为了避免指纹识别/跟踪的风险,指向设备会在每个会话开始时被分配一个新的 persistentDeviceId。
无法识别其生成设备的指针事件被分配一个 persistentDeviceId 值 0。
值
一个整数,如果无法识别生成 PointerEvent 的设备,则为 0。
注意:由于数字化仪和指向设备的硬件限制,并非所有指针事件都可能提供 persistentDeviceId,尤其是对于较旧的硬件。例如,指向设备可能无法及时向数字化仪报告其硬件 ID,导致 pointerdown 事件无法接收到 persistentDeviceId:它可能最初是 0,然后在笔划中的后续事件中更改为有效值。
示例
为每个 persistentDeviceId 分配颜色
假设有以下 HTML
html
<canvas id="inking-surface" width="1280" height="720"></canvas>
以下 JavaScript 为与画布交互的最多三个唯一指针分配不同的墨水颜色
js
const colorBlue = 0;
const colorGreen = 1;
const colorYellow = 2;
const colors = [colorBlue, colorGreen, colorYellow];
const pointerToColorMap = new Map();
let colorAssignmentIndex = 0;
const canvas = document.querySelector("#inking-surface");
// Listen for a pointerdown event and map the persistentDeviceId to a color
// if it exists and has not been mapped yet
canvas.addEventListener("pointerdown", (e) => {
if (e.persistentDeviceId && !pointerToColorMap.has(e.persistentDeviceId)) {
pointerToColorMap.set(e.persistentDeviceId, colors[colorAssignmentIndex]);
// Bump the color assignment index and loop back over if needed
colorAssignmentIndex = (colorAssignmentIndex + 1) % colors.length;
}
});
// Listen for a `pointermove` and get the color assigned to this pointer
// if persistentDeviceId exists and the pointer has been color mapped
canvas.addEventListener("pointermove", (e) => {
if (e.persistentDeviceId && pointerToColorMap.has(e.persistentDeviceId)) {
const pointerColor = pointerToColorMap.get(e.persistentDeviceId);
// Do some inking on the <canvas>
}
});
规范
| 规范 |
|---|
| 指针事件 # dom-pointerevent-persistentdeviceid |
浏览器兼容性
加载中…