大网数据广告活动
Web 标准与前端开发

PointerEvent: getCoalescedEvents() method

· 52CE 我爱测

The **`getCoalescedEvents()`** method of the PointerEvent interface returns a sequence of `PointerEvent` instances that were coalesced (merged) into a single Element/pointermove_event or Element/pointerrawupdate_event event. Instead of a stream of many Element/pointermove_event e

Pointer Events

The getCoalescedEvents() method of the PointerEvent interface returns a sequence of PointerEvent instances that were coalesced (merged) into a single Element/pointermove_event or Element/pointerrawupdate_event event. Instead of a stream of many Element/pointermove_event events, user agents coalesce multiple updates into a single event. This helps with performance as the user agent has less event handling to perform, but there is a reduction in the granularity and accuracy when tracking, especially with fast and large movements.

The getCoalescedEvents() method lets applications access all un-coalesced position changes for precise handling of pointer movement data where necessary. Un-coalesced position changes are desirable in drawing applications, for instance, where having access to all events helps to build smoother curves that better match the movement of a pointer.

For an illustration of coalesced events, see Figure 7 in the specification.

Syntax

getCoalescedEvents()

Parameters

None.

Return value

A sequence of PointerEvent instances.

Example

HTML

<canvas id="target" width="600" height="300"></canvas>

JavaScript

const canvas = document.getElementById("target");
const ctx = canvas.getContext("2d");

const pointerEvents = [];

function drawCircle(x, y, color) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // draw the last 20 events
  if (pointerEvents.length > 20) {
    pointerEvents.shift();
  }
  pointerEvents.push({ x, y, color });

  for (const pointerEvent of pointerEvents) {
    ctx.beginPath();
    ctx.arc(pointerEvent.x, pointerEvent.y, 10, 0, 2 * Math.PI);
    ctx.strokeStyle = pointerEvent.color;
    ctx.stroke();
  }
}

canvas.addEventListener("pointermove", (e) => {
  // draw a circle for the current event
  drawCircle(e.clientX, e.clientY, "black");

  const coalescedEvents = e.getCoalescedEvents();
  for (let coalescedEvent of coalescedEvents) {
    // give it an offset so we can see the difference and color it red
    drawCircle(coalescedEvent.clientX + 20, coalescedEvent.clientY + 20, "red");
  }
});

Result

Example

Specifications

Browser compatibility

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。