【问题标题】:Three.js OnDocumentMouseDown does not work with touch screen?Three.js OnDocumentMouseDown 不支持触​​摸屏?
【发布时间】:2020-03-26 17:42:19
【问题描述】:

此 Glitch 项目中的完整代码。 https://glitch.com/~quickest-catshark

我在public/components.js 中声明了一个自定义 AFRAME 组件,当用鼠标拖动时它会旋转项目。

AFRAME.registerComponent('drag-rotate-component', {
    schema: { speed: { default: 10 } },
    init: function () {
        this.ifMouseDown = false;
        this.x_cord = 0;
        this.y_cord = 0;
        document.addEventListener('mousedown', this.OnDocumentMouseDown.bind(this));
        document.addEventListener('mouseup', this.OnDocumentMouseUp.bind(this));
        document.addEventListener('mousemove', this.OnDocumentMouseMove.bind(this));
    },
    // When mouse down, save x and y coordinates of mouse position
    OnDocumentMouseDown: function (event) {
        this.ifMouseDown = true;
        this.x_cord = event.clientX;
        this.y_cord = event.clientY;
    },
    OnDocumentMouseUp: function () {
        this.ifMouseDown = false;

        // Save rotation to localstorage
        let rotation = this.el.object3D.rotation.z;
        localStorage.setItem('angle', rotation);
    },
    OnDocumentMouseMove: function (event) {
        if (this.ifMouseDown) {
            // Get difference between current mouse position and previous mouse position
            var temp_x = event.clientX - this.x_cord;
            var temp_y = event.clientY - this.y_cord;

            this.el.object3D.rotation.z = temp_x * this.data.speed / 1000;
        }
    }
});

代码在浏览器中按预期工作。

但是当我从手机中的 Chrome 访问它时,当我在该区域拖动手指时没有任何反应。也不适用于我的 Surface Pro 触控平板电脑。

如何让它在触控设备中工作?

我尝试了这个问题中给出的答案 Mouse events not working in mobile

使用event.touches[0].clientXevent.touches[0].clientY。但这些返回未定义。

【问题讨论】:

  • 触摸屏不提供鼠标事件。所以你应该使用触摸事件(touchstart、touchmove 和 touchend)。
  • 否则,你可以使用pointerevents (pointerdown,pointerup and pointermove)而且这种方式在移动设备上工作
  • 谢谢!!我使用了 touchstart、touchmove 和 touchend

标签: javascript three.js touch augmented-reality aframe


【解决方案1】:

您需要使用touchstarttouchmovetouchend 进行触摸,在这些事件中您需要使用event.touches[0].clientXclientY

此外,您可能希望您的事件处理程序不是被动的,以便在 touchstart 中您可以告诉浏览器忽略触摸,否则页面将滚动/缩放/等...

你可以在这里找到一个例子

Supporting Touch Interface in a canvas

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多