Three Js implements coordinate axes

I have been learning three js recently, so I think that as a newcomer, in daily development and learning, the coordinate axis can roughly help us locate the position and relationship of elements, so when I use Three.js to learn and develop, I basically turn on the coordinate axis. This article uses the latest version of Three.js, uses parcel to package and publish and start the service.

1. Create geometry

First create geometry, use scene and other classes to create.

import * as THREE from "three";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100)
camera.position.set(0, 0, 10);
scene.add(camera);
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const cubeMaterial = new THREE.MeshBasicMaterial({color: 0xffff00})
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
console.log(cube)
scene.add(cube);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.render(scene, camera);
document.body.appendChild(renderer.domElement)

The created image is shown in the figure:

2. Realize three-dimensional effect

After completing the above few lines of code, you can create a geometry, but because you don’t have an orbiter, you can’t see the three-dimensional style and the shape of the cube, so just add a few lines of code. At the same time, an asynchronous function should be added for each frame that the browser automatically re-renders so that it rotates with the user's mouse rotation.

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
/**
*/
function animate() {
    controls.update();
    renderer.render(scene, camera);
    requestAnimationFrame(animate);
}
animate();

3. Realize the coordinate axis

After creating the geometry and realizing the three-dimensional orbital rotation effect, you can use the coordinate axis function in three js to realize the three-dimensional coordinates to help novices judge the orientation of the geometry more quickly, so as not to get dizzy when learning.

Official documentation:

AxesHelper class

An object for simple simulation of 3 coordinate axes, red represents the X axis. Green represents the Y axis. Blue represents the Z axis.

code example

const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );

Of course, in the code of this program, renderer.render(scene, camera) must be placed in the animate function. The above realization of the coordinate axis is also the requirement, so the usage of the coordinate axis is relatively simple, just put the above function, The final image is shown in the figure.

Guess you like

Origin blog.csdn.net/qq_49491645/article/details/128756288