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 ;(