Is there a workaround for making Three.js OnDocumentMouseDown compatible with touch screens?

To view the complete code, visit this Glitch project:

Within public/components.js, I have defined a custom AFRAME component that enables rotation of an item when dragged with the mouse.

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));
    },
    // Records x and y coordinates of mouse position when mouse is clicked
    OnDocumentMouseDown: function (event) {
        this.ifMouseDown = true;
        this.x_cord = event.clientX;
        this.y_cord = event.clientY;
    },
    OnDocumentMouseUp: function () {
        this.ifMouseDown = false;

        // Saves rotation to localstorage
        let rotation = this.el.object3D.rotation.z;
        localStorage.setItem('angle', rotation);
    },
    OnDocumentMouseMove: function (event) {
        if (this.ifMouseDown) {
            // Calculates difference between current and previous mouse positions
            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;
        }
    }
});

The code functions correctly in the browser.

However, when accessed from Chrome on my mobile phone or Surface Pro touch tablet, dragging my finger on the screen yields no result.

How can I make it work on touch devices?

I attempted the solution provided in this query Mouse events not working in mobile

Using event.touches[0].clientX and event.touches[0].clientY. But these return as undefined.

Answer №1

To incorporate touch functionality, utilize the touchstart, touchmove, and touchend events. Within these events, access the touch coordinates using event.touches[0].clientX and clientY

Additionally, ensure that your event handlers are not passive to prevent unintended scrolling or zooming on touch devices.

For a practical example, refer to the following link:

Guide: Supporting Touch Interface in a canvas

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the Load More feature in jQuery to malfunction?

Attempting to create a basic "load more" feature using jquery. The concept is to mimic the functionality of traditional pagination where clicking loads additional posts from the database. Below is the javascript code: $(function(){ var count = 0; var ...

Passing dynamic scope from Angular to a directive is a seamless process

I am working with a directive that retrieves an attribute value from an http call in the following manner: Controller app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); ...

What is causing the "mb-3" class from Tailwindcss to malfunction with next/link?

The "mb-3" class from Tailwindcss in this Next.js component seems to have no effect in the Y direction. However, when using the "m-3" class, it also doesn't affect the Y direction, but instead has an impact on the X direction. impo ...

Spinning 3D Grid in Global Coordinates - Using THREE.js

I'm struggling with rotating an object in my project. I am currently utilizing THREE.Shape to define a custom shape. After creating the shape, I convert it into a Mesh and set its position to: buildingMesh.position.set(-70, -300, levelY); However, d ...

Release date approaching, but not as anticipated

Utilizing Java servlet to construct a portion of HTML and sending it with a JsonPrimitive for display in a dialog box. Here is the code snippet: ja = new JsonPrimitive( "<a href='#' onclick='return showDueDateUpdateDialogue(" + invoice. ...

Firefox and Internet Explorer do not support the functionality of HTML5 <audio> tags

My radio stream player code works perfectly on Chrome and iOS Safari, but I'm facing compatibility issues with Firefox and Internet Explorer 11. Here's a snippet from my index.php file: <script type="text/javascript" src="http://code.jquery. ...

How to create custom options in a JavaScriptMVC Controller's event listener?

When working with JavascriptMVC's Controller, they have a unique format for handling events Rather than using traditional jQuery methods $(function(){ $('#tabs').click(someCallbackFunction1) $('#tabs .tab').click(someCallback ...

Creating a basic jQuery button to switch an element's background color is a breeze

I'm new to this, so I hope this is a straightforward question. I'd like to use the bgtoggle class as a button to switch the background color of the metro class. I know I'm doing something wrong because it's not working as expected. Any ...

Show a selection of assorted files stored in the database

router.get("/alw", function(req, res){ Product.find({"category": "alw"}, function(err, allProduct){ if (err){ console.log(err) } else { res.render("products/alw", {products ...

Struggling to store the results of multiple fetch API calls in an array for future access beyond the function

fetching data from multiple APIs and storing it in an array has been a challenge. While attempting to set the data using useState, only one piece of data successfully makes it into the array. Even after trying Promise.all method, the same issue persists al ...

Using three.js, add some empty space around each face of the Icosahedron geometry to create a distinct separation between them

Looking for guidance on how to separate each face of an icosahedron, similar to the image above. Does anyone have examples or concepts on how to achieve this? Each face of my icosahedron has a unique image texture as a material, so Shadermaterial is not an ...

Learning to access a base64 encoded PDF file using JavaScript

var ajaxSettings = { url: urls.orders.list+"/"+singlePacket.requests[0].order_id+"/labels", //retrieve labels with ShipperAssigned status type: "GET", contentType: "application/json", headers: { "Authorizatio ...

The canvas doesn't seem to be rotating even after executing the setTransform

Within my HTML5 canvas, I have been experimenting with drawing lines and rotating them around the center point. My goal is to reset the canvas's transformation each time I draw, followed by re-translating/rotating the canvas. However, I have encounter ...

I am seeking a way to eliminate double quotation marks from a string without using the replace function

I need assistance in removing double quotes from the string "Hello". I have an array var ary = ['a', 'b' , 'c'] When I extract a value from the array, it returns the value in string format, such as ary[0] = "a", but I want i ...

Using AJAX in a loop presents a challenge: What is the best way to initiate an ajax request for every item in an array?

Hey there! I'm a new member of the StackOverflow community and I could really use some assistance. My current challenge involves performing an inverse geocode to retrieve addresses from coordinates. I have a functional URL that works with ajax, but I ...

What is the best way to eliminate the border color on a drop-down menu's bottom border?

I need help removing the border color from a dropdown with the style border-bottom: 1px solid rgba(0, 0, 0, 0.42); After debugging, I discovered that it is originating from the class MuiInput-underline-2593. However, the CSS class MuiInput-underline-2593 ...

Generating a JSON object based on the selection of dynamic checkboxes

Hello everyone, I am new to jQuery so please be patient with me as I embark on this journey! My goal is to structure my data in the following format... { "qualifications": [ "1", "7" ], units: [ "7", "3", "1" ] } The HTML looks like ...

One way to eliminate a prefix from a downloaded file path is by trimming the URL. For example, if you have a URL like "http://localhost

As my web app runs on port number, I am looking to download some files in a specific section. However, the download file path is being prefixed with "". <a href={file_path} download={file_name}> <Button variant={"link"}> <b>Dow ...

Unable to add personalized repository

Looking to implement a request-scoped cache for my repositories, inspired by Hibernate's first-level-cache. I have some ideas on how to achieve this and integrate it with typeorm-transactional-cls-hooked. For now, I've created a basic provider s ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...