How can you adjust the placement of a text geometry?

I have scoured through various resources like stack overflow and google in search of a solution to my problem. I have managed to successfully create a block of text in my scene that reads "Buy Here!". However, I am facing difficulty in offsetting the text by a specific number of units.

After referring to the documentation on the three.js website and exploring examples, I was able to create the text geometry with some effort. The challenge I encountered was referencing the mesh since I had generated the geometry within a function. It took me hours to realize that assigning a name to the mesh as a string would make it accessible across different levels of the hierarchy.

My current issue is trying to shift the text downwards by 5 units. Despite my attempts, I have not been successful. Every method I have tried either makes the text geometry disappear or renders my entire scene black.

Below is a snippet of my code...

I have provided the basic setup for my scene, but feel free to skip it as I believe it is unrelated to the issue...

import './style.css'
import * as THREE from 'three';
import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdb9a5bfa8a88dfde3fcfcfae3fd">[email protected]</a>/examples/jsm/controls/OrbitControls.js';
import TWEEN from 'https://cdn.jsdelivr.net/npm/@tweenjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b2f2c3e3e357531281b6a63756e756b">[email protected]</a>/dist/tween.esm.js';

//BASIC SCENE SETUP
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

//LIGHTS (POINT AND AMBIENT)
const pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.set(5, 5, 5);
const ambientLight = new THREE.AmbientLight(0xFFFFFF);
scene.add(pointLight, ambientLight);

//RESIZE WINDOW
window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    render();
}, false);

//ORBIT CONTROLS
const controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 5;
controls.maxDistance = 70;
controls.enablePan = false;
controls.enableRotate = false;
controls.enableZoom = false;
controls.target.set(0,0,-1);
camera.position.setZ(25);

window.addEventListener("click", (event) => {
        onClick(event);
    })

window.addEventListener("mousemove", onMouseMove);
    
var animate = function() {
    requestAnimationFrame(animate);
    controls.update();
    render();
    TWEEN.update();
        
};
    
function render() {
    renderer.render(scene, camera);
}
    
animate();

and here is the code where the text object is created....

var loaderF = new THREE.FontLoader();
    loaderF.load( 'https://threejs.org/examples/fonts/optimer_regular.typeface.json', function ( font ) {
        var geometry = new THREE.TextGeometry( 'Buy Here!', {
            font: font,
            size: 2.3,
            height: 0.1,
            curveSegments: 15,
            bevelEnabled: true,
            bevelThickness: 0.5,
            bevelSize: 0.31,
            bevelSegments: 7
        } );
        geometry.center();
        var material = new THREE.MeshLambertMaterial({color: 0x686868});
        var mesh = new THREE.Mesh( geometry, material );
        mesh.name = "bhText"
        scene.add( mesh );
        mesh.userData = { URL: "http://google.com"};
    } );

Here's what I have attempted.....

within "var geometry ({...});" I tried....

geometry.position.setX(-5);

which caused the text object to disappear completely, so I also attempted

geometry.position.setX = -5;

with no noticeable difference. I even removed

geometry.center();

but the outcome remained the same.

Next, I tried using

mesh.position.x = -5;

both with and without

geometry.center();

yet all attempts resulted in the text disappearing.

Subsequently, I endeavored to set the position externally by placing the following code OUTSIDE of the section enclosed by

loaderF.load ('https.....', function (font){var geometry = .....})

utilizing the knowledge I acquired....

scene.getObjectByName("bhText").position.x(-5);

however, this action caused my entire scene to turn black. I experimented with variations like

scene.getObjectByName("bhText").position.x = -5;
scene.getObjectByName("bhText").position.setX(-5);
scene.getObjectByName("bhText").position.setX = -5;
mesh.position.setX = -5;// I was fairly certain this wouldn't work due to lack of specificity 
                        // regarding the mesh name within a nested structure 

and repeated each attempt with and without

geometry.center();

nonetheless, each method resulted in a black scene.

I simply wish to move the text down by a few units. Any guidance on where in my code to set the position of the text geometry would be greatly appreciated. Thank you in advance.

Answer №1

I simply want to adjust it down by a few units.

If you want to achieve this, you can utilize mesh.position.y = - 5;. Modifying the x coordinate will relocate the mesh horizontally. Below is a detailed live demonstration based on your provided code:

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set( 0, 0, 10 );

const renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

const pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.set(5, 5, 5);

const ambientLight = new THREE.AmbientLight(0xFFFFFF);
scene.add(pointLight, ambientLight);

const loader = new THREE.FontLoader();
loader.load('https://threejs.org/examples/fonts/optimer_regular.typeface.json', function(font) {
  const geometry = new THREE.TextGeometry('Buy Here!', {
    font: font,
    size: 2,
    height: 0.5
  });
  geometry.center();
  const material = new THREE.MeshLambertMaterial({
    color: 0x686868
  });
  const mesh = new THREE.Mesh(geometry, material);
  mesh.position.y = - 1; // FIX
  
  mesh.name = "bhText"
  scene.add(mesh);
  
  renderer.render(scene, camera);
  
});
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three"></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

Incorporate Live Data into Google Charts Using Ajax Response for a Dynamic Visualization

I am struggling to successfully load a responsive Google Line Chart after an Ajax call. I have attempted to place the entire Google Chart code within the success part of the Ajax call, but it does not seem to work as expected. Below is my current Ajax code ...

Innovative tools and software employed in the creation of 3D websites

Is it possible to create stunning 3D websites similar to these examples? Chrysaora Aleksandar Rodic I am curious about the technologies required to develop websites like these and if there are any tutorials available for guidance. ...

Waiting in Python using Selenium until a class becomes visible

Currently, I am trying to extract information from a website that has multiple web pages. This is how my code appears: item_List = [] def scrape(pageNumber): driver.get(url + pageExtension + str(pageNumber)) items = driver.find_elements_by_class_ ...

I have a query related to material-ui 4, specifically the material-ui/pickers component that is reporting an error regarding a non-existent "mask" property

Recently, I upgraded a reactjs project that uses Material-UI (mui) from version 3 to version 4 by following the recommended migration guide. In the process, I also replaced material-ui-pickers 2.2.1 with @material-ui/pickers. However, after the upgrade, t ...

Another component's Angular event emitter is causing confusion with that of a different component

INTRODUCTION In my project, I have created two components: image-input-single and a test container. The image-input-single component is a "dumb" component that simplifies the process of selecting an image, compressing it, and retrieving its URL. The Type ...

express.js creating dynamic URLs causing confusion

router.get('/:username', function(req, res, next) { res.render('dashboard'); }); router.get('/', function(req, res, next) { if(req.user) // this has value res.redirect('/'+req.user); }); I'm experi ...

Avoid excessive clicking on a button that initiates an ajax request to prevent spamming

When using two buttons to adjust the quantity of a product and update the price on a digital receipt via ajax, there is an issue when users spam the buttons. The quantity displayed in the input box does not always match what appears on the receipt. For in ...

Error: The variable "weather" is not defined while using React with the weatherbit API

I'm currently developing a React application that utilizes the Weatherbit API. However, I have encountered an issue with the weather object when calling my data array. Below is the code snippet where the problem occurs: import React from "react&q ...

Retrieve data using Ajax querying from a specific data source

Currently, I am attempting to construct a custom query using Ajax to interact with PHP/MySQL. Here is what I have so far: Javascript code: var i=2; fetchFromDBPHP("name", "tblperson", "id="+i); function fetchFromDBPHP(column, table, condition) { ...

How can I streamline a kendo UI MVC project by eliminating unnecessary components?

After switching my MVC 5 project to utilize Kendo UI, I've noticed a significant increase in the number of files being used. Since there is no need for supporting other cultures at the moment, can I confidently delete the files within the messages an ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

I am struggling with sending post requests in Node.js

I am currently facing a challenge with handling form data from a webpage using Node.js and writing that data to a file. It seems like there might be an issue with how Node.js is processing my POST request, or perhaps the way I am sending the request from t ...

Removing commas and non-numeric symbols from a string using JavaScript

Stripping both a comma and any non-numeric characters from a string can be a bit tricky, especially with RegExs involved :). Is there anyone who could provide assistance on how to achieve this? I need to remove commas, dashes, and anything that is not a ...

generate a collection using a string of variables

I'm looking for a way to pass a string as the name of an array to a function, and have that function create the array. For example: createArray('array_name', data); function createArray(array_name, data){ var new_array = []; // pe ...

Store the result of the previous AJAX call in a jQuery variable and combine it with the data from the next AJAX response

I am working on a program where I retrieve price values using ajax. My goal is to add the previous price value to the current price value when it is retrieved again. The issue I am facing is that each time I get a new price value, it overrides the previou ...

Experiencing problems with lining up several circular items in a row

For my project, I am trying to showcase multiple circular shapes with percentages in a row, but I am encountering some issues. I attempted using a div with display flex, but it doesn't seem to be working as expected. Here is what I have tried so far: ...

The Twitch API is providing inaccurate channel information

Currently facing an issue while working with the Twitch API. When making a GET request to /api.twitch.tv/helix/search/channels?query=[STREAMER_NAME], it seems to be returning the wrong streamer/user. For instance: /api.twitch.tv/helix/search/channels?quer ...

Guide on setting up a configuration node in Node-RED

I am attempting to create a config node similar to this example, but it only displays a text box and not the configuration options. I want the projectid to be a config node, and despite trying various nodes with config setups, nothing seems to work for me. ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

Troubleshooting the non-functioning addEventListener in JavaScript

I am facing an issue where a function that should be triggered by a click event is not working and the console.log message does not appear <script src="e-com.js" async></script> This is how I included the javascript file in the head ...