I believe that many of you who regularly surf the Internet have seen some cool 3D effects, as a technology development, what are the high value of this technology? Today we will take you to a simple 3D effect development.
First let’s download the file threejs from Github and introduce three.js and OrbitControls.js into the HTML file. Then let’s implement a rotating cuboid step by step.
1. Create a scene object
var scene = new THREE.Scene();
Copy the code
2. Create the grid model and add it to the scene
var geometry = new THREE.BoxGeometry(400.100.100); // Create a rectangular Geometry object Geometry
var material = new THREE.MeshLambertMaterial({
color: 0x0000ff
}); // The Material object is Material
var mesh = new THREE.Mesh(geometry, material); // Mesh model object Mesh
scene.add(mesh);
Copy the code
3. Create a set point light and add it to the scene
var point = new THREE.PointLight(0xffffff);
point.position.set(400.200.300); // Point light source position
scene.add(point);
Copy the code
4. Create an ambient light and add it to the scene
var ambient = new THREE.AmbientLight(0x444444);
scene.add(ambient);
Copy the code
5. Create and set up the camera
var width = window.innerWidth; // Window width
var height = window.innerHeight; // Window height
var k = width / height; // Window width ratio
var s = 300; // 3d scene display range control coefficient, the larger the coefficient, the larger the display range
var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1.1000); // Create the camera object
camera.position.set(250.300.200); // Set the camera position
camera.lookAt(scene.position); // Set the camera orientation (the scene object to point to)
Copy the code
6. Create a Settings renderer object
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height); // Set the render area size
renderer.setClearColor(0xb9d3ff.1); // Set the background color
Copy the code
7. Insert the Canvas object into the body element
document.body.appendChild(renderer.domElement);
Copy the code
8. Set the rotation effect
let T0 = new Date(a);// Last time
function render() {
let T1 = new Date(a);// This time
let t = T1-T0; / / time
T0 = T1; // Assign this time to the last time
requestAnimationFrame(render);
renderer.render(scene, camera); // Perform render operations
mesh.rotateY(0.001 * t); // Rotate at 0.001 radians per millisecond
}
render();
Copy the code
9. Add left mouse drag and rotate, right mouse drag and zoom, and scroll wheel zoom
new THREE.OrbitControls(camera, renderer.domElement);
Copy the code
At this point, we have completed a cuboid that can be rotated. We can also use the mouse to drag and rotate the left button, drag and zoom the right button and scroll wheel.