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 |
瀏覽器相容性
載入中…