目錄
項目搭建
實現網頁簡單布局
初始化three.js基礎代碼
創(chuàng)建環(huán)境背景
加載地球模型
實現光柱效果
添加月球模型
今天簡單實現一個three.js的小Demo,加強自己對three知識的掌握與學習,只有在項目中才能靈活將所學知識運用起來,話不多說直接開始。
項目搭建
本案例還是借助框架書寫three項目,借用vite構建工具搭建vue項目,vite這個構建工具如果有不了解的朋友,可以參考我之前對其講解的文章:vite腳手架的搭建與使用 。搭建完成之后,用編輯器打開該項目,在終端執(zhí)行 npm i 安裝一下依賴,安裝完成之后終端在安裝 npm i three 即可。
因為我搭建的是vue3項目,為了便于代碼的可讀性,所以我將three.js代碼單獨抽離放在一個組件當中,在App根組件中進入引入該組件。具體如下:
<template>
<!-- 3D地球 -->
<CoolEarth></CoolEarth>
</template>
<script setup>
import CoolEarth from './components/CoolEarth.vue';
</script>
<style lang="less">
*{
margin: 0;
padding: 0;
}
</style>
實現網頁簡單布局
在HTML布局處進行設置一個loading效果,并通過一個loading.glf動態(tài)圖使loading效果更加具體,相關代碼樣式如下:
<template>
<div class="home">
<div class="canvas-container" ref="screenDom"></div>
<div class="loading" v-if="progress != 100"></div>
<div class="progress" v-if="progress != 100">
<img src="../assets/loading.gif" alt="" />
<span>地球加載中:{{ progress }}%</span>
</div>
<div class="title">酷炫3D地球</div>
</div>
</template>
<style>
body {
background-color: #000;
}
.canvas-container {
width: 100vw;
height: 100vh;
}
.home {
width: 100vw;
height: 100vh;
transform-origin: 0 0;
}
.loading {
position: fixed;
top: 0;
left: 0;
width: 1920px;
height: 1080px;
background-image: url(../assets/loading.jpg);
background-size: cover;
filter: blur(50px);
z-index: 100;
}
.progress {
position: fixed;
top: 0;
left: 0;
width: 1920px;
height: 1080px;
z-index: 101;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
color: #fff;
}
.progress > img {
padding: 0 15px;
}
.title {
width: 380px;
height: 40px;
position: fixed;
right: 100px;
top: 50px;
background-color: rgba(0, 0, 0, 0.5);
line-height: 40px;
text-align: center;
color: #fff;
border-radius: 5px;
z-index: 110;
}
</style>
初始化three.js基礎代碼
three.js開啟必須用到的基礎代碼如下:
導入three庫:
import * as THREE from 'three'
初始化場景:
const scene = new THREE.Scene()
初始化相機:
const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
camera.position.set(0,50,300)
初始化渲染器:
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(window.innerWidth,window.innerHeight)
監(jiān)聽屏幕大小的改變,修改渲染器的寬高和相機的比例:
window.addEventListener("resize",()=>{
renderer.setSize(window.innerWidth,window.innerHeight)
camera.aspect = window.innerWidth/window.innerHeight
camera.updateProjectionMatrix()
})
設置渲染函數:
const render = () =>{
controls.update();
requestAnimationFrame(render);
renderer.render(scene, camera);
}
進行掛載:
onMounted(()=>{
// 設置進度
THREE.DefaultLoadingManager.onProgress = function (item, loaded, total) {
progress.value = new Number((loaded / total) * 100).toFixed(2);
};
// 將畫布添加到頁面中
screenDom.value.appendChild(renderer.domElement)
render()
})
ok,寫完基礎代碼之后,接下來開始具體的Demo實操。
創(chuàng)建環(huán)境背景
這里通過TextureLoader加載各種類型的紋理圖像,包括JPEG、PNG、GIF等。通過TextureLoader,開發(fā)人員可以輕松地將紋理加載到自己的Three.js場景中,從而為場景增加更多的細節(jié)和視覺效果。
// 創(chuàng)建星空的背景顏色
scene.background = new THREE.Color(0x030311);
// 加載點材質紋理
const starsTexture = new THREE.TextureLoader().load("./images/stars.png");
const starsMaterial = new THREE.PointsMaterial({
size: 2,
sizeAttenuation: true, // 尺寸衰減
color: 0x4d76cf,
transparent: true,
opacity: 1,
map: starsTexture,
});
接下來通過點材質創(chuàng)建星空效果,setAttribute方法可以用于向這些BufferAttribute對象中設置頂點屬性數據,BufferAttribute是在Three.js等WebGL引擎中用于描述幾何體或粒子的渲染數據結構,也是WebGL中頂點緩存對象(VBO)中存儲頂點數據的方式之一:
// 使用點材質創(chuàng)建星空效果
const vertices = [];
for (let i = 0; i < 500; i++) {
const vertex = new THREE.Vector3();
vertex.x = 800 * Math.random() - 400;
vertex.y = 800 * Math.random() - 400;
vertex.z = 800 * Math.random() - 400;
vertices.push(vertex.x, vertex.y, vertex.z);
}
// 星空效果
let starsGeometry = new THREE.BufferGeometry();
starsGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(vertices), 3)
);
let stars = new THREE.Points(starsGeometry, starsMaterial);
scene.add(stars);
加載地球模型
接下來依然通過TextureLoader加載各種類型的紋理圖像:
// 創(chuàng)建地球
let earthGeometry = new THREE.SphereGeometry(50, 32, 32);
let earthTexture = new THREE.TextureLoader().load("./images/map.jpg");
let earthMaterial = new THREE.MeshBasicMaterial({
map: earthTexture,
});
let earth = new THREE.Mesh(earthGeometry, earthMaterial);
scene.add(earth);
接下來在原有地球的基礎上再加一層發(fā)光球體的殼,使地球更具有美感:
// 發(fā)光地球
let lightTexture = new THREE.TextureLoader().load("./images/earth.jpg");
let lightEarthGeometry = new THREE.SphereGeometry(53, 32, 32);
let lightEarthMaterial = new THREE.MeshBasicMaterial({
map: lightTexture,
alphaMap: lightTexture,
blending: THREE.AdditiveBlending,
transparent: true,
});
let lightEarth = new THREE.Mesh(lightEarthGeometry, lightEarthMaterial);
scene.add(lightEarth);
接下來通過 Sprite 將Sprite 對象圖像資源打包在一張貼圖上,然后在需要渲染Sprite 的時候使用不同的紋理坐標選取對應的圖像片段進行繪制。
// 添加地球內外發(fā)光精靈
let spriteTexture = new THREE.TextureLoader().load("./images/glow.png");
let spriteMaterial = new THREE.SpriteMaterial({
map: spriteTexture,
color: 0x4d76cf,
transparent: true,
depthWrite: false,
depthTest: false,
blending: THREE.AdditiveBlending,
});
let sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(155, 155, 0);
scene.add(sprite);
接下來接著使用該函數使其內發(fā)光:
// 內發(fā)光
let spriteTexture1 = new THREE.TextureLoader().load("./images/innerGlow.png");
let spriteMaterial1 = new THREE.SpriteMaterial({
map: spriteTexture1,
color: 0x4d76cf,
transparent: true,
depthWrite: false,
depthTest: false,
blending: THREE.AdditiveBlending,
});
let sprite1 = new THREE.Sprite(spriteMaterial1);
sprite1.scale.set(128, 128, 0);
scene.add(sprite1);
let scale = new THREE.Vector3(1, 1, 1);
實現光柱效果
通過for循環(huán)實現30個光柱效果的展示,這里依然通過TextureLoader加載各種類型的紋理圖像:
for (let i = 0; i < 30; i++) {
// 實現光柱
let lightPillarTexture = new THREE.TextureLoader().load(
"./images/light_column.png"
);
let lightPillarGeometry = new THREE.PlaneGeometry(3, 20);
let lightPillarMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
map: lightPillarTexture,
alphaMap: lightPillarTexture,
transparent: true,
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide,
depthWrite: false,
});
let lightPillar = new THREE.Mesh(lightPillarGeometry, lightPillarMaterial);
lightPillar.add(lightPillar.clone().rotateY(Math.PI / 2));
// 設置光柱的位置
let lat = Math.random() * 180 - 90;
let lon = Math.random() * 360 - 180;
let position = lon2xyz(60, lon, lat);
lightPillar.position.set(position.x, position.y, position.z);
lightPillar.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
position.clone().normalize()
);
scene.add(lightPillar);
}
接下來利用貼圖給地球的每個光柱添加光圈效果,這里利用gsap動畫庫實現:
// 創(chuàng)建波紋擴散效果
let circlePlane = new THREE.PlaneGeometry(6, 6);
let circleTexture = new THREE.TextureLoader().load("./images/label.png");
let circleMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
map: circleTexture,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
side: THREE.DoubleSide,
});
let circleMesh = new THREE.Mesh(circlePlane, circleMaterial);
circleMesh.rotation.x = -Math.PI / 2;
circleMesh.position.set(0, -7, 0);
lightPillar.add(circleMesh);
gsap.to(circleMesh.scale, {
duration: 1 + Math.random() * 0.5,
x: 2,
y: 2,
z: 2,
repeat: -1,
delay: Math.random() * 0.5,
yoyo: true,
ease: "power2.inOut",
});
添加月球模型
接下來依然通過TextureLoader加載各種類型的紋理圖像:
// 繞地球運行的月球
let moonTexture = new THREE.TextureLoader().load("./images/moon.jpg");
let moonMaterial = new THREE.MeshStandardMaterial({
map: moonTexture,
emissive: 0xffffff,
emissiveMap: moonTexture,
});
let moonGeometry = new THREE.SphereGeometry(5, 32, 32);
let moon = new THREE.Mesh(moonGeometry, moonMaterial);
moon.position.set(150, 0, 0);
scene.add(moon);
接下來實現月球環(huán)模型:
// 創(chuàng)建月球環(huán)
let moonRingTexture = new THREE.TextureLoader().load("./images/moon_ring.png");
let moonRingMaterial = new THREE.MeshBasicMaterial({
map: moonRingTexture,
transparent: true,
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide,
depthWrite: false,
opacity: 0.5,
});
let moonRingGeometry = new THREE.RingGeometry(145, 155, 64);
let moonRing = new THREE.Mesh(moonRingGeometry, moonRingMaterial);
moonRing.rotation.x = -Math.PI / 2;
scene.add(moonRing);
接下來通過gsap動畫庫當月球順時針繞地球無限勻速旋轉運動下去:
let time = {
value: 0,
};
gsap.to(time, {
value: 1,
duration: 10,
repeat: -1,
ease: "linear",
onUpdate: () => {
moon.position.x = 150 * Math.cos(time.value * Math.PI * 2);
moon.position.z = 150 * Math.sin(time.value * Math.PI * 2);
moon.rotation.y = time.value * Math.PI * 8;
},
});
效果完成之后,我們在一開始設置的掛載時顯示進度也就有效果了,如下:
文章來源:http://www.zghlxwxcb.cn/news/detail-476792.html
demo做完,給出本案例的完整代碼:(獲取素材也可以私信博主)文章來源地址http://www.zghlxwxcb.cn/news/detail-476792.html
<template>
<div class="home">
<div class="canvas-container" ref="screenDom"></div>
<div class="loading" v-if="progress != 100"></div>
<div class="progress" v-if="progress != 100">
<img src="../assets/loading.gif" alt="" />
<span>地球加載中:{{ progress }}%</span>
</div>
<div class="title">酷炫3D地球</div>
</div>
</template>
<script setup>
import * as THREE from 'three'
import { ref,onMounted } from 'vue'
import { gsap } from 'gsap'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
let screenDom = ref(null)
let progress = ref(0);
// 經緯度轉換函數
const lon2xyz = (R,longitude,latitude) =>{
let lon = ( longitude * Math.PI ) / 180 // 轉弧度值
const lat = (latitude * Math.PI) / 180 // 轉弧度值
lon = -lon // js坐標系z坐標軸對應經度-90度,而不是90度
// 經緯度坐標轉球面坐標計算公式
const x = R * Math.cos(lat) * Math.cos(lon)
const y = R * Math.sin(lat)
const z = R * Math.cos(lat) * Math.sin(lon)
// 返回球面坐標
return new THREE.Vector3(x,y,z)
}
// 創(chuàng)建場景
const scene = new THREE.Scene()
// 創(chuàng)建相機
const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
camera.position.set(0,50,300)
// 創(chuàng)建渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(window.innerWidth,window.innerHeight)
// 創(chuàng)建控制器
const controls = new OrbitControls(camera,renderer.domElement)
controls.autoRotate = true
window.addEventListener("resize",()=>{
renderer.setSize(window.innerWidth,window.innerHeight)
camera.aspect = window.innerWidth/window.innerHeight
camera.updateProjectionMatrix()
})
// 創(chuàng)建渲染函數
const render = () =>{
controls.update();
requestAnimationFrame(render);
renderer.render(scene, camera);
}
onMounted(()=>{
// 設置進度
THREE.DefaultLoadingManager.onProgress = function (item, loaded, total) {
progress.value = new Number((loaded / total) * 100).toFixed(2);
};
// 將畫布添加到頁面中
screenDom.value.appendChild(renderer.domElement)
render()
})
// 創(chuàng)建星空的背景顏色
scene.background = new THREE.Color(0x030311);
// 加載點材質紋理
const starsTexture = new THREE.TextureLoader().load("./images/stars.png");
const starsMaterial = new THREE.PointsMaterial({
size: 2,
sizeAttenuation: true, // 尺寸衰減
color: 0x4d76cf,
transparent: true,
opacity: 1,
map: starsTexture,
});
// 使用點材質創(chuàng)建星空效果
const vertices = [];
for (let i = 0; i < 500; i++) {
const vertex = new THREE.Vector3();
vertex.x = 800 * Math.random() - 400;
vertex.y = 800 * Math.random() - 400;
vertex.z = 800 * Math.random() - 400;
vertices.push(vertex.x, vertex.y, vertex.z);
}
// 星空效果
let starsGeometry = new THREE.BufferGeometry();
starsGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(vertices), 3)
);
let stars = new THREE.Points(starsGeometry, starsMaterial);
scene.add(stars);
// 創(chuàng)建地球
let earthGeometry = new THREE.SphereGeometry(50, 32, 32);
let earthTexture = new THREE.TextureLoader().load("./images/map.jpg");
let earthMaterial = new THREE.MeshBasicMaterial({
map: earthTexture,
});
let earth = new THREE.Mesh(earthGeometry, earthMaterial);
scene.add(earth);
// 發(fā)光地球
let lightTexture = new THREE.TextureLoader().load("./images/earth.jpg");
let lightEarthGeometry = new THREE.SphereGeometry(53, 32, 32);
let lightEarthMaterial = new THREE.MeshBasicMaterial({
map: lightTexture,
alphaMap: lightTexture,
blending: THREE.AdditiveBlending,
transparent: true,
});
let lightEarth = new THREE.Mesh(lightEarthGeometry, lightEarthMaterial);
scene.add(lightEarth);
// 添加地球內外發(fā)光精靈
let spriteTexture = new THREE.TextureLoader().load("./images/glow.png");
let spriteMaterial = new THREE.SpriteMaterial({
map: spriteTexture,
color: 0x4d76cf,
transparent: true,
depthWrite: false,
depthTest: false,
blending: THREE.AdditiveBlending,
});
let sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(155, 155, 0);
scene.add(sprite);
// 內發(fā)光
let spriteTexture1 = new THREE.TextureLoader().load("./images/innerGlow.png");
let spriteMaterial1 = new THREE.SpriteMaterial({
map: spriteTexture1,
color: 0x4d76cf,
transparent: true,
depthWrite: false,
depthTest: false,
blending: THREE.AdditiveBlending,
});
let sprite1 = new THREE.Sprite(spriteMaterial1);
sprite1.scale.set(128, 128, 0);
scene.add(sprite1);
let scale = new THREE.Vector3(1, 1, 1);
for (let i = 0; i < 30; i++) {
// 實現光柱
let lightPillarTexture = new THREE.TextureLoader().load(
"./images/light_column.png"
);
let lightPillarGeometry = new THREE.PlaneGeometry(3, 20);
let lightPillarMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
map: lightPillarTexture,
alphaMap: lightPillarTexture,
transparent: true,
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide,
depthWrite: false,
});
let lightPillar = new THREE.Mesh(lightPillarGeometry, lightPillarMaterial);
lightPillar.add(lightPillar.clone().rotateY(Math.PI / 2));
// 設置光柱的位置
let lat = Math.random() * 180 - 90;
let lon = Math.random() * 360 - 180;
let position = lon2xyz(60, lon, lat);
lightPillar.position.set(position.x, position.y, position.z);
lightPillar.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
position.clone().normalize()
);
scene.add(lightPillar);
// 創(chuàng)建波紋擴散效果
let circlePlane = new THREE.PlaneGeometry(6, 6);
let circleTexture = new THREE.TextureLoader().load("./images/label.png");
let circleMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
map: circleTexture,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
side: THREE.DoubleSide,
});
let circleMesh = new THREE.Mesh(circlePlane, circleMaterial);
circleMesh.rotation.x = -Math.PI / 2;
circleMesh.position.set(0, -7, 0);
lightPillar.add(circleMesh);
gsap.to(circleMesh.scale, {
duration: 1 + Math.random() * 0.5,
x: 2,
y: 2,
z: 2,
repeat: -1,
delay: Math.random() * 0.5,
yoyo: true,
ease: "power2.inOut",
});
}
// 繞地球運行的月球
let moonTexture = new THREE.TextureLoader().load("./images/moon.jpg");
let moonMaterial = new THREE.MeshStandardMaterial({
map: moonTexture,
emissive: 0xffffff,
emissiveMap: moonTexture,
});
let moonGeometry = new THREE.SphereGeometry(5, 32, 32);
let moon = new THREE.Mesh(moonGeometry, moonMaterial);
moon.position.set(150, 0, 0);
scene.add(moon);
// 創(chuàng)建月球環(huán)
let moonRingTexture = new THREE.TextureLoader().load("./images/moon_ring.png");
let moonRingMaterial = new THREE.MeshBasicMaterial({
map: moonRingTexture,
transparent: true,
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide,
depthWrite: false,
opacity: 0.5,
});
let moonRingGeometry = new THREE.RingGeometry(145, 155, 64);
let moonRing = new THREE.Mesh(moonRingGeometry, moonRingMaterial);
moonRing.rotation.x = -Math.PI / 2;
scene.add(moonRing);
let time = {
value: 0,
};
gsap.to(time, {
value: 1,
duration: 10,
repeat: -1,
ease: "linear",
onUpdate: () => {
moon.position.x = 150 * Math.cos(time.value * Math.PI * 2);
moon.position.z = 150 * Math.sin(time.value * Math.PI * 2);
moon.rotation.y = time.value * Math.PI * 8;
},
});
</script>
<style>
body {
background-color: #000;
}
.canvas-container {
width: 100vw;
height: 100vh;
}
.home {
width: 100vw;
height: 100vh;
transform-origin: 0 0;
}
.loading {
position: fixed;
top: 0;
left: 0;
width: 1920px;
height: 1080px;
background-image: url(../assets/loading.jpg);
background-size: cover;
filter: blur(50px);
z-index: 100;
}
.progress {
position: fixed;
top: 0;
left: 0;
width: 1920px;
height: 1080px;
z-index: 101;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
color: #fff;
}
.progress > img {
padding: 0 15px;
}
.title {
width: 380px;
height: 40px;
position: fixed;
right: 100px;
top: 50px;
background-color: rgba(0, 0, 0, 0.5);
line-height: 40px;
text-align: center;
color: #fff;
border-radius: 5px;
z-index: 110;
}
</style>
到了這里,關于Three.js--》實現3d地球模型展示的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!