Threejs - 幾行代碼帶你創(chuàng)建三維地球

需要具備哪些知識 ?
前端開發(fā)中的一些基礎(chǔ)知識,html,css,javascript
vue 基本用法 (注意: 本實(shí)例是基于vue來做的,也可以采用原生js的方式開發(fā),看個人喜好)
先來看下效果吧
開發(fā)前準(zhǔn)備
1. 一張地球全景平面圖

2. 搭建一個三維場景,場景中添加網(wǎng)格模型(前面幾講有具體講到如何搭建一個三維場景以及添加網(wǎng)格模型,添加相機(jī),燈光,渲染器等)
3. 紋理加載器 (TextureLoader)
廢話就講到這里了,直接上代碼看效果吧
<template><div ref="content"></div></template><script>// 引入threejsimport * as THREE from "../../public/build/three";//鼠標(biāo)控制import { OrbitControls } from "../../public/example/jsm/controls/OrbitControls.js";export default {components: {},data() {return {// 創(chuàng)建一個場景scene: null,// 創(chuàng)建一個相機(jī)camera: null,// 創(chuàng)建一個渲染器renderer: null,// 模型對象mesh: null,// 平面plane: null,// 點(diǎn)光源point: null,// stepstep:0};},mounted() {this.init();},methods: {// 初始化init() {// 初始化容器var content = this.$refs.content;// 創(chuàng)建一個場景this.scene = new THREE.Scene();this.scene.background = new THREE.Color("#000");// 創(chuàng)建幾何體var geometry = new THREE.SphereGeometry(30, 50, 50);// 紋理加載器 ( 此處加載貼圖 )var texture = new THREE.TextureLoader().load(require('./Earth.png'));// 幾何體材質(zhì)對象var material = new THREE.MeshLambertMaterial({map: texture});// 創(chuàng)建網(wǎng)格模型對象this.mesh = new THREE.Mesh(geometry, material);//設(shè)置幾何體位置this.mesh.position.x = 0;this.mesh.position.y = 10;this.mesh.position.z = 0;this.scene.add(this.mesh);// 創(chuàng)建點(diǎn)光源var point = new THREE.PointLight("#FFF");point.position.set(40, 200, 30);this.point = point;this.scene.add(point);const sphereSize = 10;const pointLightHelper = new THREE.PointLightHelper(point, sphereSize);this.scene.add(pointLightHelper);//創(chuàng)建環(huán)境光var ambient = new THREE.AmbientLight(0x444444);this.scene.add(ambient);// 創(chuàng)建一個相機(jī)this.camera = new THREE.PerspectiveCamera(70,window.innerWidth / window.innerHeight,1,10000);this.camera.position.set(-50, 50, 50);this.camera.lookAt(0, 0, 0);//坐標(biāo)軸輔助器,X,Y,Z長度30// var axes = new THREE.AxesHelper(300);// this.scene.add(axes);// 輔助網(wǎng)格// let gridHelper = new THREE.GridHelper(100, 100);// this.scene.add(gridHelper);// 創(chuàng)建渲染器this.renderer = new THREE.WebGLRenderer();this.renderer.setSize(window.innerWidth, window.innerHeight);this.renderer.setClearColor(0xb9d3ff, 1);//插入 dom 元素content.appendChild(this.renderer.domElement);let controls = new OrbitControls(this.camera, this.renderer.domElement);controls.addEventListener("resize", this.render(), false);},render() {this.renderer.render(this.scene, this.camera);// 自動旋轉(zhuǎn)動畫this.mesh.rotateY(0.01);requestAnimationFrame(this.render);}}};</script><style lang="scss" scoped></style>
評論
圖片
表情
