Placing an image on a three.js cube using overlay does not function properly

I attempted to superimpose an image onto a cube by utilizing code from GPT chat and Blackbox AI, but in both cases, I encountered a black screen. I saved the code in a file named test.html and tested it on Google Chrome and Opera GX browsers, only to be met with a persistent black screen. Even running the code through a server on Node JS did not resolve the issue.

GPT CHAT:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Three.js cube</title>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b7f637960604548525d5f425e52">[email protected]</a>/build/three.min.js"></script>
    <style>
        body { margin: 0; }
        canvas { display: block; }
    </style>
</head>
<body>

<div id="canvas-container"></div>

<script>
   
    const scene = new THREE.Scene();

    
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 5;

  
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById('canvas-container').appendChild(renderer.domElement);

   
    const textureLoader = new THREE.TextureLoader();
    const texture = textureLoader.load('C:\\Users\\User\\Desktop\\test.jpg');

    
    const material = new THREE.MeshBasicMaterial({ map: texture });

    
    const geometry = new THREE.BoxGeometry();
    
    
    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    
    let isDragging = false;
    let previousMousePosition = {
        x: 0,
        y: 0
    };
    function onMouseMove(event) {
        const deltaMove = {
            x: event.offsetX - previousMousePosition.x,
            y: event.offsetY - previousMousePosition.y
        };
        if (isDragging) {
            const deltaRotationQuaternion = new THREE.Quaternion()
                .setFromEuler(new THREE.Euler(
                    toRadians(deltaMove.y * 1),
                    toRadians(deltaMove.x * 1),
                    0,
                    'XYZ'
                ));
            cube.quaternion.multiplyQuaternions(deltaRotationQuaternion, cube.quaternion);
        }
        previousMousePosition = {
            x: event.offsetX,
            y: event.offsetY
        };
    }
    function onMouseDown(event) {
        isDragging = true;
        previousMousePosition = {
            x: event.offsetX,
            y: event.offsetY
        };
    }
    function onMouseUp() {
        isDragging = false;
    }
    document.addEventListener('mousedown', onMouseDown, false);
    document.addEventListener('mouseup', onMouseUp, false);
    document.addEventListener('mousemove', onMouseMove, false);

    
    function toRadians(degrees) {
        return degrees * (Math.PI / 180);
    }

    
    function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
    }

    
    animate();
</script>
</body>
</html>

`

BLACKBOX AI:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Three.js Image Rotation</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script>
     
      const scene = new THREE.Scene();
      const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      camera.position.z = 5;
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      
      const loader = new THREE.TextureLoader();
      const texture = loader.load('C:\\Users\\User\\Desktop\\test.jpg');

      
      const geometry = new THREE.PlaneGeometry(1, 1);
      const material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide });
      const mesh = new THREE.Mesh(geometry, material);
      scene.add(mesh);

      
      function handleMouseMove(event) {
        const mouseX = (event.clientX / window.innerWidth) * 2 - 1;
        const mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
        mesh.rotation.y = Math.atan2(mouseX, mouseY);
      }

      renderer.domElement.addEventListener('mousemove', handleMouseMove, false);

      
      function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
      }

      animate();
    </script>
  </body>
</html>

Despite testing the code across different devices, I continued to face the challenge of a persistent black screen.

Answer №1

My suspicion is that the texture path may be incorrect...

<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06726e7463634636283730372836">[email protected]</a>/build/three.module.js",
      "three/addons/": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfbba7bdaaaa8fffe1fef9fee1ff">[email protected]</a>/examples/jsm/"
    }
  }
</script>
<div id="canvas-container"></div>
<script type="module">
import * as THREE from "three";

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.z = 2;

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("canvas-container").appendChild(renderer.domElement);

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load(  "https://pixabay.com/get/gefe3a53651a7efc132c4c30d5ba86d19fb4f7e5c2cc5a4fb6db51aeac76f4be39457f4b70271b1cb3df2a69c69754bf9_640.jpg"
);

const material = new THREE.MeshBasicMaterial({ map: texture });

const geometry = new THREE.BoxGeometry();

const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

let isDragging = false;
let previousMousePosition = {
  x: 0,
  y: 0,
};
function onMouseMove(event) {
  const deltaMove = {
    x: event.offsetX - previousMousePosition.x,
    y: event.offsetY - previousMousePosition.y,
  };
  if (isDragging) {
    const deltaRotationQuaternion = new THREE.Quaternion().setFromEuler(
      new THREE.Euler(
        toRadians(deltaMove.y * 1),
        toRadians(deltaMove.x * 1),
        0,
        "XYZ"
      )
    );
    cube.quaternion.multiplyQuaternions(
      deltaRotationQuaternion,
      cube.quaternion
    );
  }
  previousMousePosition = {
    x: event.offsetX,
    y: event.offsetY,
  };
}
function onMouseDown(event) {
  isDragging = true;
  previousMousePosition = {
    x: event.offsetX,
    y: event.offsetY,
  };
}
function onMouseUp() {
  isDragging = false;
}
document.addEventListener("mousedown", onMouseDown, false);
document.addEventListener("mouseup", onMouseUp, false);
document.addEventListener("mousemove", onMouseMove, false);

function toRadians(degrees) {
  return degrees * (Math.PI / 180);
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();
</script>

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

In jQuery selectors, providing two variables may not yield any results, yet inputting the same string manually produces the desired output

For instance: let a = "1234"; let b = "line1\\\\.5"; Now, this particular code line: "#" + a + b; Produces the following string "#1234line1\\.5" And when I use it in the select ...

Accessing Google Maps offline using HTML5 is a convenient and helpful

Our team is working on an HTML5 application that includes a Google map feature for changing search locations. Recently, we've added an offline version of the app as well. Is there a way to cache the Google map so that when the app is offline, it can s ...

The styled-components seem to be having trouble injecting the necessary CSS to handle all the various props

I am curious to understand the potential reasons for styled-components not injecting all the necessary CSS into a page's header. In an existing project, I have defined a simple button like this: const Button = styled.button` background-color: ...

A Guide to Sorting Nested Lists with SortableJS and jQuery

I have been experimenting with SortableJS and jQuery SortableJS Binding in order to create a nested list, capture the new order of the list and its children (resembling a hierarchical structure) using console.log(). I attempted the solution provided in th ...

Building a Many-to-Many Relationship in Node.js Using Sequelize.js

As I utilize the sequelize node.js module to structure schema in Postgres SQL, I have defined two schemas for Project and my users. Project Schema module.exports = function(sequelize, DataTypes) { var project = sequelize.define('project', { ...

To determine whether a variable is an integer in PHP

Is there a more elegant solution to this problem? if( $_POST['id'] != (integer)$_POST['id'] ) echo 'not an integer'; I attempted if( !is_int($_POST['id']) ) However, I encountered issues with is_int(). This ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

Stop the form from refreshing the page after submitting a post request to the backend API

I am facing an issue with my React front end and Express back end integration. I have a form in my front end that sends data to the API using two buttons - Submit and Close. The Close button works perfectly by closing the overlay without leaving the page, ...

What causes two elements with display: inline-block; position: absolute; to overlap instead of appearing side by side?

It is recommended to use position: relative; in order to achieve inline block behavior for both elements and prevent them from overlapping. This positions the elements inline next to each other as they are recognized as blocks. When using position: absolu ...

The <servicename> is inaccessible within an error function in Angular2

I encountered an unusual issue in angular2. While the code below is functioning correctly: loginResult.subscribe( (data) => this.response = data, (err) => this._ajaxService.handleError(err, 'A string to summarize th ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

The CSS overlay effect refuses to shut down

Greetings everyone, I'm new around here so please bear with me. I am encountering an issue wherein the overlay only works in one direction - it appears when the button is clicked, but nothing happens when attempting to close it. I have tried adjustin ...

Steps for configuring type definitions for an Apollo error response

Apollo's documentation explains that an error response can take the following form: { "data": { "getInt": 12, "getString": null }, "errors": [ { "message": "Failed to get s ...

What is the best way to retrieve EXIF data following the AJAX loading of images?

Currently, I am developing a swipe-able wine image viewer for NapaWapa.com and it's functioning quite smoothly: The challenge I'm facing is related to using a jquery plugin to extract the exif data from the images in the gallery. Unfortunately, ...

Encountering a problem while verifying pattern using regular expressions

I'm facing an issue when manually checking if my inputs match the specified patterns. Below is the function I am using for this check: if (!$element.attr("pattern")) return true; let pattern = $element.attr("pattern"); le ...

What does dist entail?

I am currently utilizing gulp to create a distribution folder (dist) for my Angular application. After consolidating all the controllers/services JS files and CSS, I am now faced with handling the contents of the bower folder. In an attempt to concatenat ...

Scrolling of inner div element is controlled by the outer scrollbar

I have a div element that can scroll vertically, but I want the scrollbar to be positioned outside of the div just like in a regular webpage. The scrollbar should only affect this particular div and not the entire page. <div id="outer"> <div ...

What is the best way to trigger the onclick event before onblur event?

I have two elements - an anchor with an onclick function and an input with an onfocus event. The anchor is toggled by the input button; meaning, when the button is in focus, the anchor is displayed, and when it loses focus, the anchor is hidden. I'm l ...

Using JavaScript to modify a section of an anchor link attribute

I am looking to dynamically update part of the URL when a specific radio button is selected. There are three purchase links, each representing a different amount. After choosing an animal, I need to select one of the three amounts to spend. How can I modi ...

Establishing a dynamic database feature (such as a real-time leader board) on a website

Recently, I designed a fun JavaScript game for my website and now I am contemplating adding a leaderboard feature. However, I am unsure about which type of database would be the best fit - MongoDB, SQLite, or something else entirely. I have heard that SQ ...