threeJs学习 贴图 :地球
<template>
<div class="scene_box">
<p>创建纹理贴图TextureLoader</p>
<div class="canvas"></div>
</div>
</template>
<script setup>
import { nextTick } from "vue";
import img from "../../js/chapter5/earth.jpg";
import * as THREE from "three";
// 引入threejs 的扩展库 相机轨道控件
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
nextTick(() => {
// ******************创建一个场景*************
const geometry = new THREE.SphereGeometry(80); //球体
//纹理贴图加载器TextureLoader
const texLoader = new THREE.TextureLoader();
// .load()方法加载图像,返回一个纹理对象Texture
const texture = texLoader.load(img);
const material = new THREE.MeshBasicMaterial({
// color: 0x00ffff,
// 设置纹理贴图:Texture对象作为材质map属性的属性值
map: texture, //map表示材质的颜色贴图属性
});
// material.map = texture;//也可以通过map属性直接设置,材质的参数设置一样
const mesh = new THREE.Mesh(geometry, material);
//场景
const scene = new THREE.Scene();
scene.add(mesh); //模型对象添加到场景中
//辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(150);
scene.add(axesHelper);
//光源设置
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(100, 60, 50);
scene.add(directionalLight);
const ambient = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambient);
//渲染器和相机
let dom = document.querySelector(".canvas");
const width = dom.offsetWidth;
const height = dom.offsetHeight;
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
camera.position.set(292, 223, 185);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
dom.appendChild(renderer.domElement);
// 渲染循环
function render() {
scene.rotateY(0.005);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
// const controls = new OrbitControls(camera, renderer.domElement);
// 画布跟随窗口变化
window.onresize = function () {
renderer.setSize(dom.offsetWidth, dom.offsetHeight);
camera.aspect = dom.offsetWidth / dom.offsetHeight;
camera.updateProjectionMatrix();
};
renderer.setPixelRatio(window.devicePixelRatio);
});
</script>
<style scoped>
.canvas {
width: 80vw;
height: 60vh;
}
</style>