Three.js OnDocumentMouseDown无法在触摸屏上使用吗?

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

此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。但是这些返回未定义。

javascript three.js touch augmented-reality aframe
1个回答
1
投票

您需要使用touchstarttouchmovetouchend进行触摸,在这些情况下,您将使用event.touches[0].clientXclientY

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

您可以在这里找到示例

Supporting Touch Interface in a canvas

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