- 前段时间因公司需求,需要做一个前端展示的效果,其中有一部分需要有一个转动的三维地球,想了想Cesium.js可以实现,Three.js同样也可以。
(three)
(cesium)
-好像两者都只是一个简单的地球,初始化一下就可以了。实际上确实也是一个简单的地球 QAQ~
贴上three的代码
<template>
<canvas ref="canvas" class="w100"></canvas>
</template>
<script>
import * as THREE from "three";
export default {
data() {
return {
scene: null,
camera: null,
renderer: null,
earth: null,
starPoints: null,
cloudMesh:null
};
},
mounted() {
this.initBg();
window.addEventListener("resize", this.resize);
},
beforeDestroy() {
window.removeEventListener("resize", this.resize);
},
methods: {
initBg() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(
75,
this.$refs.canvas.offsetWidth / window.innerHeight,
0.1,
1000
);
this.camera.position.z = 10;
this.renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true,
canvas: this.$refs.canvas,
});
this.renderer.setSize(this.$refs.canvas.offsetWidth, window.innerHeight-40);
const textureLoader = new THREE.TextureLoader();
const earthImg = require("@/assets/image/earth/earth.jpg");
const earthImg2 = require("@/assets/image/earth/earth2.jpg");
const earthImg3 = require("@/assets/image/earth/earth3.jpg");
const cloudImg = require("@/assets/image/earth/clouds.png");
const geometry = new THREE.SphereGeometry(4, 28, 28);
const material = new THREE.MeshBasicMaterial({
specular: 0x7c7c7c,
shininess: 15,
map: textureLoader.load(earthImg),
specularMap: textureLoader.load(earthImg2),
normalMap: textureLoader.load(earthImg3),
normalScale: new THREE.Vector2(0.85, -0.85),
});
// material.map.colorSpace = THREE.SRGBColorSpace;
this.earth = new THREE.Mesh(geometry, material);
this.scene.add(this.earth);
const cloudGeometry = new THREE.SphereGeometry(4.02, 200, 200);
const cloudTexture = new THREE.TextureLoader().load(cloudImg);
const cloudMaterial = new THREE.MeshBasicMaterial({
map: cloudTexture,
transparent: true,
});
this.cloudMesh = new THREE.Mesh(cloudGeometry, cloudMaterial);
this.scene.add(this.cloudMesh);
const light = new THREE.PointLight(0xffffff, 1, 0);
light.position.set(0, 0, 0);
this.scene.add(light);
this.animate();
},
animate() { //这是自定义的动画方法,根据y轴横向转动。
requestAnimationFrame(this.animate);
this.earth.rotation.y += 0.0008;
this.cloudMesh.rotation.y += 0.0005;
this.renderer.render(this.scene, this.camera);
},
resize(e) { //这是随着视窗改变从而初始化地球的方法 上面监听的resize
if (window.innerWidth < 1100) {
this.$refs.canvas.width = 100;
this.$refs.canvas.height = 100;
this.$refs.canvas.classList.remove("w100");
} else {
this.camera.aspect = window.innerWidth / 2 / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth / 2, window.innerHeight);
}
},
},
};
</script>
<style>
.w100 {
width: 100%;
height: 100%;
}
</style>
关于Cesium的,也很简单,我的需求就是中间有个转动的地球,当鼠标移入地球的盒子中,地球停止转动,当鼠标进入,又继续执行转动。当双击地球的时候,3D会切到2.5D然后显示相关的图层。这里就不贴代码,因为用的框架做的,方法都封装了 没有参考意义。转动的方法Cesium也有,相关的例子可以进cesium的examples去瞅瞅。