Javascript 移动事件(鼠标移动、指针移动、触摸移动)不精确

问题描述 投票:0回答:1

我正在尝试用 JavaScript 创建白板。我正在使用这个代码:

let lastTimestamp = 0;
const fps = 1000/60;
document.addEventListener("pointermove", moveMouse, false);
function moveMouse (e) {
    e.preventDefault();
    const now = performance.now();
    if (now - lastTimestamp >= fps) {
        lastTimestamp = now;
        if (current_stroke != null) {
            current_stroke.addPoint(e.x, e.y, e.pressure);
            if (e.pressure == 0) mouseUp();
        }
    }
}

它效果很好,直到你开始写一些东西或做一些更复杂的事情。例如,出于某种原因,它总是难以处理硬角度或绘图。这并不是说它没有足够的笔画分辨率,你可以绘制非常详细的曲线,但不知何故,硬角度只会让它变得混乱。 Hard angles image

绘制文本时这也是一个大问题,它工作正常,直到它停止触发事件几毫秒,足以使文本在某些部分上正常,而在其他部分上块状。 Stops firing the event image

使用鼠标、手写笔或触摸不会改变结果,也不会更改浏览器。

有谁知道如何修复它或更好的方法来创建它?

谢谢你。

javascript html canvas
1个回答
0
投票

答案是詹姆斯的评论。有一个条件检查笔划点之间的间距。

if (x - lastPoint[0] > spacing || y - lastPoint[1] > spacing) {
// Add point

问题是,显然这必须是绝对值才能得到距离。当行程上升时,这会导致问题,因为它得到负值,因此不满足条件。

if (Math.abs(x - lastPoint[0]) > spacing || Math.abs(y - lastPoint[1]) > spacing) {
// Add point

这是我从来没有看过的东西,因为在调试它时,我在pointermove上添加了一个console.log,我可以看到它在获得块状笔划时没有打印。无论如何,谢谢大家。

© www.soinside.com 2019 - 2024. All rights reserved.