其他一些答案表明这是因为处理程序函数缓慢。在我的测试中,无论是count++
在处理程序中,还是在更昂贵的画布绘制调用中,都没有任何区别- 在这两种情况下,10 秒内生成的事件数量约为 500。但是,它可能会在较慢的计算机上产生影响。
显然,大多数鼠标/指针每秒仅向操作系统报告其位置不到 100 次,因此这可能甚至不受浏览器控制。
您可能想研究一下新PointerEvent.getCoalescedEvents()
方法。来自 MDN 文档:
接口的getCoalescedEvents()
方法PointerEvent
返回PointerEvent
合并到分派pointermove
事件中的所有实例的序列。
下面是一个例子:
window.addEventListener("pointermove", function(event) {
let events = event.getCoalescedEvents();
for(let e of events) {
draw(e.pageX, e.pageY);
}
});
但是,在对此进行测试后,它似乎很少合并我计算机上的事件。不过,它在速度较慢的计算机上可能更有用。所以现在最好的方法可能是使用ctx.lineTo
,或类似的方法(arcTo
也许)。这是一个简单的工作画布绘图演示,结合getCoalescedEvents
了lineTo
:
<canvas id="canvas" style="touch-action:none; width:100vw; height:100vh; position:fixed; top:0; left:0; right:0; bottom:0;"></canvas>
<script>
let mouseIsDown = false;
let ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener("pointerdown", function(e) {
ctx.beginPath();
ctx.moveTo(e.pageX, e.pageY);
mouseIsDown = true;
});
window.addEventListener("pointerup", function(e) {
mouseIsDown = false;
});
window.addEventListener("pointermove", function(event) {
if(mouseIsDown) {
let events = event.getCoalescedEvents();
for(let e of events) {
ctx.lineTo(e.pageX, e.pageY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.pageX, e.pageY);
}
}
});
</script>