What are the steps to implement a personalized canvas in ThreeJS?

Struggling with creating a basic ThreeJS application that displays 3D text on the scene. The examples on the website are too complex for beginners like me. I'm finding it hard to make the scene appear without using tricks and I want to customize my own canvas element with CSS properties.

Below is the code I've written to display a cube in the scene.

import * as THREE from 'three';
import 'bootstrap';
import css from '../css/custom_css.css';

let scene = new THREE.Scene();

let WIDTH = window.innerWidth;
let HEIGHT = window.innerHeight;

let camera = new THREE.PerspectiveCamera(75, WIDTH / HEIGHT, 0.1, 1000);
let renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(WIDTH, HEIGHT);
renderer.setClearColor(0xE8E2DD, 1);

// Append Renderer to DOM
document.body.appendChild( renderer.domElement );

// Create the shape
let geometry = new THREE.BoxGeometry(1, 1, 1);
// Create a material, colour or image texture
let material = new THREE.MeshBasicMaterial( {
    color: 0xFF0000,
    wireframe: true
});

// Cube
let cube = new THREE.Mesh(geometry, material);
scene.add(cube);

let material_text = new THREE.MeshPhongMaterial({
    color: 0xdddddd
});

var loader = new THREE.FontLoader();

loader.load( 'fonts/helvetiker_regular.typeface.json', function ( font ) {

    var geometry = new THREE.TextGeometry( 'Hello three.js!', {
        font: font,
        size: 80,
        height: 5,
        curveSegments: 12,
        bevelEnabled: true,
        bevelThickness: 10,
        bevelSize: 8,
        bevelOffset: 0,
        bevelSegments: 5
    } );

    let textMesh = new THREE.Mesh(geometry, material_text);
    scene.add(textMesh);

    console.log('added mesh')
} );


camera.position.z = 5;

// Game Logic
let update = function(){
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.005;
};

// Draw Scene
let render = function(){
  renderer.render(scene, camera);
};

// Run game loop, update, render, repeat
let gameLoop = function(){
    requestAnimationFrame(gameLoop);

    update();
    render();
};

gameLoop();

I suspect the issue lies with the canvas because many suggest simply adding

var renderer = new THREE.WebGLRenderer( { canvas: my_canvas } );

, which doesn't work for me. I know this because if I remove that and keep

// Append Renderer to DOM
document.body.appendChild( renderer.domElement );

, then I can see the objects in my scene.

Why can't I place the scene on my canvas?

My canvas element is defined as

<!--                            Canvas                         -->
<canvas id="my_canvas" class="container-fluid h-100 w-100 p-0 position-fixed" style="background-color: white; z-index: -1"> </canvas>

Edit: Also, why is only the cube showing in the scene and not the text? Thanks

Edit: Tried using canvas: document.getElementById('my_canvas') but it didn't work ;(

Answer №1

To achieve your goal, follow these 3 steps in order:

  1. Begin by creating a canvas within the document.
  2. Use JavaScript to select your canvas.
  3. Provide the canvas selector to the ThreeJS renderer.

In your HTML code:

<canvas id="my_canvas"></canvas>
<script>
    // Make sure to place your script tags at the end of the document to ensure proper functionality of selectors.
</script>

In your JavaScript code:

// Retrieve the canvas from the document
var canvasRef = document.getElementById("my_canvas");

// Then, include it in the renderer constructor
var renderer = new THREE.WebGLRenderer({
    antialias:true,
    canvas: canvasRef
});

Once you have completed these steps successfully, you can apply custom CSS rules as follows:

#my_canvas {
    width: 100%;
    height: 100%;
}

Answer №2

I remember facing a similar issue in the past, the solution was to exclude position-fixed from the CSS classes applied to the canvas element. (As mentioned by @Mugen87).

<canvas id="my_canvas" class="container-fluid h-100 w-100 p-0" style="background-color: white; z-index: -1"> </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

Unraveling XML with XSLT 2.0 to Remove Normalization

I need help with denormalizing XML using XSLT 2.0. Here is an example of the XML and the desired output. I am looking for assistance in creating the XSLT code to achieve this. Denormalization should only apply to tags that start with "Change" and leave ot ...

Error Message: The function "menu" is not a valid function

I've encountered an issue with a function not being called properly. The error message states "TypeError: menu is not a function." I attempted to troubleshoot by moving the function before the HTML that calls it, but unfortunately, this did not resolv ...

ReactJS input range issue: Cannot preventDefault within a passive event listener invocation

I've been encountering some issues with the react-input-range component in my React App. It functions perfectly on larger viewports such as PCs and desktops, but on smaller devices like mobile phones and tablets, I'm seeing an error message "Unab ...

What makes fastify-plugin better than simply calling a regular function?

I recently came across a detailed explanation of how fastify-plugin operates and its functionality. Despite understanding the concept, I am left with a lingering question; what sets it apart from a standard function call without using the .register() metho ...

Empty results in NgRx Parameterized Selector

Having trouble implementing a parameterized query in NgRx and receiving empty results. Check out the StackBlitz version of the code here: https://stackblitz.com/edit/ngrx-parameterized-query Update to Reducer Code export const userAdapter = createEntity ...

Issue with click event for submit button in ASP.Net following a change in dropdown list index using JavaScript

Currently, I have an asp.net application where a confirmation popup alert is displayed when the selected index changes to a specific value ("Cancelled") in a dropdown list. <asp:DropDownList ID="ddlStatus" runat="server" CssClass="selectstyle" DataText ...

The div display property in a media query

Below is the css styling for a specific div: .titleHome { position: absolute; top: 10px; left: 12px; width: 80px; height: 50px; z-index: 8; } My goal is to hide this div when the screen width exceeds 900px, and make it visible whe ...

Communication breakdown between components in Angular is causing data to not be successfully transmitted

I've been attempting to transfer data between components using the @Input method. Strangely, there are no errors in the console, but the component I'm trying to pass the data from content to header, which is the Header component, isn't displ ...

Pass the value from JavaScript to PHP

I am looking to insert a JavaScript value into PHP: var temp = $('#field_id').val().charAt(0); The 'temp' variable returns values ranging from 1 to 4. var value = "<?php echo $variable[temp]['id']; ?>"; How can I re ...

Using Javascript in the Model-View-Controller (MVC) pattern to load images stored as byte

Despite the numerous solutions available on Stack Overflow, I am still unable to get any of them to work... I am faced with the challenge of setting the "src" attribute of an image tag using a byte array obtained from an ajax call to my controller in Java ...

Error message: Unable to set the uploaded file in the specified state within a React application

I am currently working on a react application that involves file uploads. My goal is to update the state variable with the uploaded file in either .docx or .pdf format as soon as it is uploaded. However, when I try to set the state, it shows up as undefine ...

What is the best way to incorporate Vue Apollo into a Vue Vite project?

I'm currently working on integrating Vue Apollo into a Vite project using the composition API. Here is how my main.js file looks: import { createApp } from 'vue' import App from './App.vue' import * as apolloProvider from '../ ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Trouble with formatting a HTML form

I have been working on dynamically creating HTML forms using a function called makeInput(). However, I am facing an issue where the text input boxes are appearing next to each other when I click the "Add Course" button, instead of one per line. Below is ...

Can we load the form using an ajax request and then submit the form using ajax as

So I have a situation where I am loading a form into a page using an ajax call as shown below: $('.ajax_click').on('click', function(event) { event.preventDefault(); /* Act on the event */ var getmsgtoload = $(this).find(&ap ...

Creating a dynamic form field using JavaScript

I'm struggling with a JavaScript issue that requires some assistance. I have a form sending an exact number of inputs to be filled to a PHP file, and now I want to create a preview using jQuery or JavaScript. The challenge lies in dynamically capturin ...

Having trouble getting Vue async components to function properly with Webpack's hot module replacement feature

Currently, I am attempting to asynchronously load a component. Surprisingly, it functions perfectly in the production build but encounters issues during development. During development, I utilize hot module replacement and encounter an error in the console ...

Using Lodash to Substitute a Value in an Array of Objects

Looking to update the values in an array of objects, specifically the created_at field with months like 'jan', 'Feb', etc.? One way is to loop through using map as demonstrated below. However, I'm curious if there's a more co ...

What is the best way to allocate values within a for loop?

I am in the process of designing an interface for individuals who have no background in programming. My goal is to allow them to input certain details, and then be able to simply copy and paste the code to make everything function seamlessly. Here is a sa ...

Using JavaScript values retrieved from a database to dynamically adjust the options in the second dropdown menu based on the selection made in the

I am currently working on a feature that involves populating two dropdown menus with values from a database. The idea is that when an option is selected in the first dropdown, the second dropdown should dynamically display relevant values based on that s ...