I am experiencing difficulties getting my three.js application to run smoothly on mobile devices

My iPhone running on iOS 13.7 has been able to flawlessly run all the three.js examples, including fat lines and orbit controls.

However, when I try to run my own code on mobile, it doesn't seem to work. You can check out the source code and the uploaded website for reference. It works fine on Edge and Chrome browsers on my Windows computer.

I followed this answer that suggested adding "use strict"; to all .js files, even for imported modules, but it didn't help.

Any advice or clues on what might be causing my JavaScript code to break on mobile devices?

This is how I included the modules in hopf.js:

import * as THREE from './three.module.js';
import { OrbitControls } from '/OrbitControls.js';
import { LineMaterial } from './LineMaterial.js';
import { LineGeometry } from './LineGeometry.js';
import { Line2 } from './Line2.js';
import { GUI } from './dat.gui.module.js';
import Stats from './stats.module.js'

Here's a snippet from index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <style>
        body { margin: 0; }
        canvas { display: block; }
    </style>
    <title>Document</title>
</head>
<body>
    <script type = "module" src = "hopf.js"></script>
</body>

The init-function looks like this:

function init() {

    // Camera
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.001, 1000);
    camera.position.x = -3;
    camera.position.y = 0;
    camera.position.z = 0;
    camera.lookAt(0,0,0);

    // Orthographic camera, focusing on the 2-sphere base space
    var aspect = window.innerWidth / window.innerHeight;
    var scale = 3;
    
    orthCamera = new THREE.OrthographicCamera(-aspect*scale, aspect*scale, 1*scale, -1*scale, 0.001, 1000);
    orthCamera.position.set(5,5,10);
    orthCamera.lookAt(0,0,0);

    // Scene setup
    scene = new THREE.Scene();
    orthScene = new THREE.Scene();

    // Objects
    baseSpace_geometry = new THREE.SphereGeometry(1,30,30);
    baseSpace_material = new THREE.MeshBasicMaterial({color: 0xfafafa});
    baseSpace_material.transparent = true;
    
    baseSpace = new THREE.Mesh(baseSpace_geometry,baseSpace_material);
    baseSpace.position.x = 4.5;
    baseSpace.position.y = -1;
    orthScene.add(baseSpace);
    
    // Renderer
    renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth , window.innerHeight );
    renderer.autoClear = false;

    // Controls
    controls = new OrbitControls(camera, renderer.domElement);

    window.addEventListener('resize', onWindowResize, false);
    document.body.appendChild(renderer.domElement);

    stats = new Stats();
    document.body.appendChild(stats.dom);

    initGui();

    baseSpaceCircles.push(new baseSpaceCircle(0, 2*Math.PI, 10, defaultRotation, new THREE.Vector3(0,0,0), 0.0));

    onWindowResize();
    render();
}

Answer №1

It seems that your website is not functioning properly on Firefox as well. Upon checking the console, an error was detected:

Uncaught SyntaxError: private fields are not currently supported

This issue stems from using #distanceToCenter_radians; in your code, as the # symbol is reserved for declaring private fields. To enhance browser compatibility, I suggest removing this symbol. According to the support table, private fields do not function on Firefox and Safari versions below 14.0.

UPDATE

After rectifying the bug on Firefox, a similar problem occurred while testing on Safari, with an error displayed in the console:

https://i.sstatic.net/nYXFx.png

The error arises from the use of public class fields in your baseSpaceCircle class, which Safari does not support until version 14.0+.

// These class variables won't work:
class baseSpaceCircle {
    distanceToCenter; // <- Safari 13 thinks this is a class method
    distanceToCenter_radians;
    circumference;
    // ...
}

Attempting to initialize them did not resolve the issue:

class baseSpaceCircle {
    distanceToCenter = 0;
    distanceToCenter_radians = 0;
    circumference = 0;
    // ...

Unfortunately, this approach led to another error... https://i.sstatic.net/0jINf.png ...and further investigation led me to this explanation. Essentially, your application utilizes advanced JavaScript features that are not universally supported by all browsers, including Safari on both iOS and MacOS. Private fields, public class fields, and similar functionalities pose compatibility challenges due to their recent introduction.

Solution 1:

To address this issue, declare these variables within the constructor using this.xxx:

class baseSpaceCircle {
    constructor(distanceToCenter, /*...*/) {
        this.distanceToCenter;
        this.distanceToCenter_radians;
        this.circumference;
        this.pointCount;
    }
    //...

This approach proves successful in Safari! https://i.sstatic.net/uwlc3.png

Solution 2:

I highly recommend utilizing a transpiler such as Babel, which can convert modern code into older JavaScript supported by all browsers. This simplifies programming with features like classes, arrow functions, async/await, etc., eliminating compatibility concerns.

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

Is there a quick method to "install or fetch" for NodeJS?

I'm currently working on a piece of code that has the ability to proactively address missing dependencies without any need for manual intervention. What I envision is something along the lines of var aes256 = require_or_install('nodejs-aes256&ap ...

Ways to execute the pdf.js node demonstrations?

I've been attempting to run the pdf.js node examples, specifically getinfo.js. Unfortunately, I encountered an issue that resulted in the following error: C:\Repositories\pdf.js>node getinfo.js node:internal/modules/cjs/loader:1080 thro ...

Dealing with AngularJS variables that are undefined when attempting to refresh the view from the controller

I am currently learning AngularJS and attempting to transform my webpage using the "angular way" instead of relying on jQuery. However, I am facing some challenges in understanding how to achieve this. This is how my HTML looks: <body style="padding-t ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

Switch the Ionic Slide Box to the "does-continue" setting

Currently in the process of constructing a slide-box containing numerous items. I've borrowed the code from the example provided here for an infinite number of items, and it's performing well. However, I have a considerable yet finite amount of ...

Incorporate a dropdown menu based on the selection made in another dropdown menu

I have a scenario on my website where I want to dynamically add select boxes based on the value selected in the previous one. Here is the code snippet: <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"> </script> & ...

Adaptive Website displayed within an iframe

Currently, I have a responsive website that can be viewed here. The main objective is to embed this site into an iframe while maintaining its responsiveness. I attempted embedding my site in JSFiddle for testing purposes, which you can see here. However ...

Utilizing JSON data to create dynamic HTML content for Isotope.js filtering

UPDATE: After struggling to understand the previous answers, I have revised this question for clarity. As a beginner, I hope this simplified version can benefit others like me... I want to utilize isotope.js to showcase specific data from a JSON source (r ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

How can I accurately determine the true dimensions of an image in Angular, including any resizing that may

Here is an image: @ViewChild('image') readonly photo: ElementRef; The HTML code for the image is: <img #photo class="pic" /> How can I find the original size (width, height) as well as the resized dimensions after applying CSS a ...

Exploring the concept of 'JavaScript with Scope' within the MongoDB environment

Within the link provided at https://docs.mongodb.com/manual/reference/bson-types/, it discusses JavaScript with Scope as a potential data type found in documents. I have some inquiries: (1) Could you explain what exactly JavaScript with scope entails? ( ...

Tips for choosing an option from a dropdown menu and triggering the onchange event using Jquery

I'm facing a challenge in selecting dropdown options dynamically based on data received from a social networking plugin. I also need to trigger an onchange event to populate successive dropdown menus. The data I am working with includes country, stat ...

When rendering a PNG image with an alpha channel, three.js has been reported to leak pixels from the videocard

Struggling to come up with a suitable title for my question here.. I'm encountering an issue when loading PNG files from an external URL, specifically with one PNG that has a non-power-of-two alpha channel created in Gimp. When I load and use this PNG ...

Error: The $filter function in AngularJS is not recognized

I have been attempting to inject a filter into my controller and utilize it in the following manner: angular .module('graduateCalculator', []) .filter('slug', function() { return function(input) { ...

How to retrieve the scrolling distance in Internet Explorer using JavaScript

I am working with a scrollable div and I need to find a way to conditionally stop it from scrolling. Here is an example of the code: if(theDiv.scrollTop + theDiv.clientHeight + thisScrollAmount > theDiv.scrollHeight) StopScrolling(); How can I de ...

When external API validation fails, the JavaScript form is submitted

I am working on implementing form validation using an external email validation API. Below is the form tag I am using: <form class="form-horizontal" role="form" onsubmit="return validateForm()" method="post"> Here is a snippet of my JavaScript co ...

As the second line of Javascript code is being executed, the first line is still

I have a task where I need to execute a SQL SELECT statement and save the results. Then, those results need to be passed into a function to generate a graph using the data points provided. Refer to the code snippet below for details. var dataKWhr = getCov ...

Conceal the heading 4 element when a specific text is searched

I have a search script that filters the text, but I want to hide the h4 element at the top of each ol. How can I achieve this? The issue I'm facing is that while the text gets filtered correctly, the h4 element (which should be hidden) remains visibl ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Prevent clicking through slides on React by disabling the Swiper feature

Is there a way to handle the global document click event (using React hook useClickAway) so that it still fires even when clicking on a slide? For example, think of a circle in the header like an avatar dropdown - when you click on it, a menu pops up. Th ...