Modify the appearance of a specific side of a CircleGeometry shape over a set period of time

As a novice in the world of Three.js, I recently completed a crash course and now have a basic understanding of its capabilities.

I managed to create a rotating disc on my website with my own image/texture, but I would like to change the texture/image on one side at set time intervals. For example, after 5 seconds, switch it out, then switch back after another 5 seconds, and continue this cycle.

Since I am new to this technology, I am not sure how to achieve this. However, I do have some knowledge of basic to semi-advanced JavaScript concepts.

Below is the code snippet that I have been working on:

// 3D Cube created in three.js

// Select the div with the specified ID.
let cube3d = document.querySelector('#cube3d')
// These values depend on the CSS for properly positioning the cube.
let CANVAS_WIDTH = 450;
let CANVAS_HEIGHT = 450;

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(75, (CANVAS_WIDTH / CANVAS_HEIGHT), 0.1, 1000);
let renderer = new THREE.WebGLRenderer();
let geometry = new THREE.CircleGeometry(6, 32);

// Images to load on each face of the cube.
let cubeMaterials = [
    new THREE.MeshBasicMaterial({
        map: new THREE.TextureLoader().load('{{ "/assets/gifs/me.jpg" }}'),
        side: THREE.DoubleSide
    })
];
let material = new THREE.MeshFaceMaterial(cubeMaterials);
let circle = new THREE.Mesh(geometry, material);

// Rotation speeds
let rotX = 0.008;
let rotY = 0.009;

//Cube
scene.add(circle);

camera.position.z = 10;

renderer.setSize(CANVAS_WIDTH, CANVAS_HEIGHT);
cube3d.appendChild(renderer.domElement);

animate();

function animate() {
    circle.rotation.x += rotX;
    circle.rotation.y += rotY;
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}

// Responsive resizing
window.addEventListener('resize', function() {
    let width = CANVAS_WIDTH;
    let height = CANVAS_HEIGHT;
    renderer.setSize(width, height);
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
});

Answer №1

It seems like your variable naming convention might be a bit confusing as you switch between using cubeXX and circleXX interchangeably. To simplify things, here is some pseudocode that demonstrates loading 2 textures and swapping them every 5 seconds using the setInterval function:

// Load two different textures
let textureLoader = new THREE.TextureLoader();
let texture1 = textureLoader.load("/assets/gifs/yo.jpg");
let texture2 = textureLoader.load("/assets/gifs/yoTambien.jpg");

// Create geometry, material, and mesh for a circle
let circleGeom = new THREE.CircleGeometry(6, 32);
let circleMat = new THREE.MeshBasicMaterial({
    map: texture1,
    side: THREE.DoubleSide
});
let circleMesh = new THREE.Mesh(circleGeom, circleMat);
scene.add(circleMesh);

// Set an interval to swap textures every 5000 milliseconds
window.setInterval(swapTextures, 5000);

// Check active texture and switch it with the other one
function swapTextures() {
    if (circleMat.map === texture1) {
        circleMat.map = texture2;
    } else {
        circleMat.map = texture1;
    }
}

On another note, may I ask which crash course you followed? It's worth noting that MeshFaceMaterial has been deprecated since 2015 as mentioned in this source.

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 the process for linking dynamic content to document-ready events?

When it comes to jQuery and JavaScript, I admittedly struggle a bit. I have a specific question but can't seem to find the right search terms to get me there. It involves using either .trigger() or on(), but I'm unsure of the correct implementati ...

Retrieve an array of 16 elements using React in a TypeScript environment

Exploring the new React 16 feature to return array elements within the render method is throwing a TypeScript error stating "Property 'type' is missing in type 'Element[]'" const Elements: StatelessComponent<{}> = () => ([ & ...

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

Using a render target causes certain elements of my visual graphics to become hidden

Hey there, I've been experimenting with render targets lately and encountered some issues. I've put together a simplified example below: init = function() { // RENDERER canvas = document.getElementById("mycanvas"); renderer = new THREE ...

Tips for obtaining the iframe #document with cheeriojs?

I've been struggling to scrape the anime videos page [jkanime], specifically with extracting the mp4 video formats embedded in an iframe #document. Despite trying to use cheerio for querying, I've only managed to retrieve src links from Facebook ...

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

What is the technique for positioning a camera directly above an object in a 3D environment?

Currently, I am delving into the world of ThreeJS and grappling with some basic principles. Let's say there is a camera positioned in 3D space, focusing on a specific target (specified in the camera.target property). The coordinates of the camera are ...

Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default. Current Progress function $onEachFeature( ...

The TypeScript error reads: "An element is implicitly assigned the 'any' type because an expression of type 'any' cannot be used to index a specific type."

[Hey there!][1] Encountering this TypeScript error message: { "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 0: { image: string; title: string; text: string; }; 1: { ...

Convert a 2D Canvas into a Three.js Canvas

I am currently working on developing a simple 2D game using Three.js. My approach involves utilizing the X and Y positions of objects for movement, while keeping the Z position at zero. To enable 2D camera movement with right-click panning and mouse wheel ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

WebGl - Perspective skewing perspective

I've been working on implementing an oblique projection in WebGL, but I'm encountering an issue where the projection appears identical to ortho. Here's the snippet of code setting up the projection matrix: mat4.identityMatrix(pMatrix); ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

What are the steps to successfully install OpenCV (javascript edition) on Internet Explorer 11?

I'm currently experiencing issues with getting the OpenCV javascript version to function properly on IE11 for contour detection. While my code runs smoothly on all other up-to-date browsers, I am encountering errors such as: TypeError: Object doesn&a ...

The Socket IO Client is receiving a different object than the one that was sent by the Server

My server side code is sending an object to the client side, but the object received by the client is completely different from what was sent. Let me elaborate: Code Server side code: //Setting up the example var response={}; response.models=[]; respo ...

The average calculation malfunctioning after adjusting the input data

I am a beginner with AngularJS and facing an issue. I have a list of cities for which I need to calculate the average temperature. However, after editing the temperature values in the city list, the function that computes the average temperature is giving ...

problems with using array.concat()

I am attempting to reverse a stream of data using a recursive call to concatenate a return array. The instructions for this problem are as follows: The incoming data needs to be reversed in segments that are 8 bits long. This means that the order of thes ...

Create a JavaScript variable every few seconds and generate a JSON array of the variable whenever it is updated

My variable, which consists of random numbers generated by mathrandom every second, such as "14323121", needs to be saved to an array for the latest 10 updates. function EveryOneSec() { var numbers = Math.random(); // I want to create an array from th ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

What is the best way to simultaneously check two conditions in Vue.js?

In my current scenario, I am facing a challenge with checking both conditions simultaneously. If an attachment exists in the request but the attachment field does not exist in the form, it should display a message in the modal. Similarly, if body text exis ...