1、 First, we need to create a Vue project
This paper mainly records the process of building panorama in detail, so building Vue project is not described too much.
2、 Install three js
npm install three --save
npm install three-trackballcontrols --save
npm install three-orbit-controls --save
npm i three-obj-mtl-loader --save
npm i three-fbx-loader --save
npm i three-stats --save
three-trackballcontrols:Trackball control, the most commonly used control, can easily move, pan and zoom the scene with the mouse.
three-orbit-controls :3D scene operation plug-in. In fact, when NPM installs three, the corresponding plug-in has been downloaded on node_ Three / examples / JSM / controls / orbitcontrols can be found in the modules folder, and the corresponding plug-ins can also be found in this path.
three-obj-mtl-loader:load. Obj model file Plug in for MTL material information file.
three-fbx-loader:Plug in for FBX model files.
three-stats:The performance detection plug-in can monitor the number of frames of animation.
3、 Renderer renderer, scene scene, camera
Three. JS,sceneIt can be understood as a container. We can put the required objects into the scene.cameraThe function of is to take a suitable scene in the scene and shoot it.Renderer The function of is to render the pictures taken by the camera to the browser for display.
4、 Concrete implementation
- Introduce dependency
import * as THREE from "three";
import * as ThreeStats from 'three-stats'
const OrbitControls = require('three-orbit-controls')(THREE);
- Define variables
data() {
return {
Renderer: '', // renderer
Scene: '', // scene
Light: '', // light source
Camera: '', // camera
Controls: '', // controller
Stats: '', // performance monitor
Mygroup: '', // model group
Action: '', // controls the value of the animation
Clock: '', // clock
Mixer: '', // mixed instance
Rotateanimate: '', // rotate animation
Srotate: 1, // enable rotation
}
}
- Initialize renderer
rendererInit() {
var width = 1000;
var height = 800;
this.renderer = new THREE.WebGLRenderer();
this.renderer.setClearColor(0xffffff);
this.renderer.setSize(width, height);
//Through this$ Refs gets the dom of the page and binds the renderer
this.$refs.threeDom.appendChild(this.renderer.domElement);
}
- Initialize scene
sceneInit() {
this.scene = new THREE.Scene();
var ambient = new THREE. AmbientLight(0x444444, 3); // Add light color and light intensity
var axisHelper = new THREE. AxesHelper(600); // Add auxiliary coordinate system
this.scene.add(ambient, axisHelper);
},
AmbientLight:Ambient light will uniformly illuminate all objects in the scene. It cannot be used to cast shadows because it has no direction.
AmbientLight( color : Integer, intensity : Float )
Color – (optional parameter) the RGB value of the color. The default value is 0xFFFFFF.
Intensity – (optional parameter) the intensity of the light. The default value is 1.
AxesHelper:An object used to simply simulate 3 axes. Red represents the X axis, green represents the Y axis, and blue represents the Z axis.
AxesHelper( size : Number )
Size — (optional) indicates the length of the line segment representing the axis Default to1。
- Create model
modelling(){
this.mygroup = new THREE.Group();
var textureLoader = new THREE. TextureLoader(); // Create texture map
var img = textureLoader.load(require('../../public/img/home3.jpeg'));
var geometry = new THREE. SphereGeometry(130, 256, 256); // Sphere mesh model
var material = new THREE.MeshLambertMaterial({
Map: IMG, // set color map attribute value
side: THREE. Doubleside, // double sided rendering
});
var meshSphere = new THREE. Mesh(geometry, material); // Mesh model object mesh
meshSphere. Name = 'sphere container';
this.mygroup.add(meshSphere);
var canvasText = this. Getcanvers ('enter ')// Generate a canvers text pattern object
var texture = new THREE.CanvasTexture(canvasText);
var geometryText = new THREE.PlaneGeometry(16, 10, 60, 60);
var materialText = new THREE.MeshPhongMaterial({
Map: texture, // set texture map
side: THREE. Doubleside, // double sided rendering
});
var meshText = new THREE.Mesh(geometryText, materialText);
meshText. Name = 'enter the door';
meshText.position.set(40, 20, -90)
this.mygroup.add(meshText);
this.scene.add(this.mygroup);
this. addAnimation(); // Add and turn on animation
this.refresh();
}
//Generate a canvers pattern
getcanvers(text) {
var canvasText = document.createElement("canvas");
var c = canvasText.getContext('2d');
//Rectangular area fills background
c.fillStyle = "#FFFFFF"; // Canver background
c.fillRect(0, 0, 300, 200); // Generate a rectangle
c.translate(160, 80);
c.fillStyle = "#000000"; // Text fill color
c. Font = "bold 100px Arial"// Font style settings
c.textBaseline = "middle"; // Text and
c.textAlign = "center"; // Text centered
c.fillText(text, 0, 0);
return canvasText;
}
SphereGeometry:A class for generating spheres.
SphereGeometry(radius : Float, widthSegments : Integer, heightSegments : Integer, phiStart : Float, phiLength : Float, thetaStart : Float, thetaLength : Float)
Radius – radius of the sphere, which is 1 by default.
Widthsegments – number of horizontal segments (segments along the longitude), the minimum value is 3, and the default value is 8.
Highsegments – number of vertical segments (segments along the weft), the minimum value is 2, and the default value is 6.
Phistart – specifies the starting angle of the horizontal (longitude), and the default value is 0..
Philength – specifies the size of the horizontal (Meridian) scanning angle, and the default value is math PI * 2。
Thetastart – specifies the starting angle of the vertical (weft), which is 0 by default.
Thetalongth – specifies the size of the vertical (weft) scanning angle. The default value is math PI。
MeshLambertMaterial:A non glossy surface material without specular highlights.
MeshLambertMaterial( parameters : Object )
.map : Texture。 Color map. The default is null.
.side : Integer。 Defines which side to render – front, back, or both. The default is three FrontSide。 Other options are three Backside and three DoubleSide。
CanvasTexture:Create a texture map from the canvas element.
PlaneGeometry:A class for generating planar geometry.
MeshPhongMaterial:A material used for glossy surfaces with specular highlights.
- Initialize camera
cameraInit() {
var width = 800; // Window width
var height = 800; // Window height
this. camera = new THREE. PerspectiveCamera(90, width / height, 1, 1000); // Use perspective camera
this. camera. position. set(0, 0, 10); // Set camera position
this. camera. lookAt(new THREE.Vector3(0, 0, 0)); // Camera look
}
PerspectiveCamera:Perspective camera.
PerspectiveCamera( fov : Number, aspect : Number, near : Number, far : Number )
FOV – vertical field of view angle of camera cone
Aspect – aspect ratio of the visual cone of the camera
Near – near end face of camera cone
Far – far end face of camera cone
- Initialize the controller (3D scene operation plug-in)
controlInit() {
this. controls = new OrbitControls(this.camera, this.$refs.threeDom); // Initialize controller
this. controls. target. set(0, 0, 0); // Set the focus of the controller so that the controller rotates around this focus
this. controls. minDistance = 10; // Set the shortest distance to move (zero by default)
this. controls. maxPolarAngle = Math. PI; // Distance around vertical track (range is 0-math.pi, default is math. PI)
this. controls. maxDistance = 30; // Sets the maximum distance to move (the default is infinite)
this. controls. enablePan = false; // Disable the right-click function
this. controls. addEventListener('change', this.refresh); // Monitor mouse and keyboard events so that the whole control can be dragged
},
- Rotate animation
addAnimation() {
this.clock = new THREE.Clock();
var times = [0, 3600]; // Create frame animation sequence
var position_x = [0, 360];
var keyframe = new THREE.KeyframeTrack('meshSphere.rotation[y]', times, position_x);
var duration = 100; // Duration
var cilp = new THREE. AnimationClip('sphereRotate', duration, [keyframe]); // Clip keyframe object
this. mixer = new THREE. AnimationMixer(this.mygroup); // Animation blend instance
this.action = this.mixer.clipAction(cilp);
this. action. timeScale = 1; // Playback speed
this. action. setLoop(THREE.LoopPingPong). play(); // Start playing and cycle back and forth between the start point and the end point like a table tennis ball
this. animate(); // Turn on animation
},
//Loop rendering
animate() {
this.rotateAnimate = requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
this.update();
},
Clock:Used to track time.
KeyframeTrack:Keyframetrack is a timing sequence of keyframes. It consists of a list of time and related values, which is used to move a specific attribute of an object.
KeyframeTrack( name : String, times : Array, values : Array, interpolation : Constant )
Name – identifier of the keyframetrack.
Times – the time array of key frames, which is internally converted to float32array.
Values – an array of values related to time points in the time array, which is internally converted to float32array.
Interpolation – the type of interpolation used.
AnimationClip:Animation clip is a reusable set of keyframe tracks that represents animation.
AnimationClip( name : String, duration : Number, tracks : Array )
Name – the name of this clip.
Duration – duration in seconds. If a negative number is passed in, the duration will be calculated from the passed in array.
Tracks – an array of keyframetracks.
AnimationMixer:The animation mixer is a player for animating specific objects in a scene. When multiple objects in the scene animate independently, each object can use the same animation mixer.
- Finally, initialize the load
init() {
this.$ refs. threeDom. addEventListener('dblclick', this.onMouseDblclick); // Listen for double click events
this. rendererInit(); // Create renderer
this. sceneInit(); // Create a scene that contains lights and auxiliary coordinate systems
this. cameraInit(); // Create camera
this. controlInit(); // Initialize controller
this. propertyInit(); // Performance monitoring
this. modelling(); // Model building
}
Reference article:
https://juejin.cn/post/6927193628724953096
https://blog.csdn.net/ithanmang/article/details/84062933