webgl_geometry_colors

ThreeJS 官方案例学习(webgl_geometry_colors)

1.效果图

在这里插入图片描述

2.源码

<template>
	<div>
		<div id="container"></div>
	</div>
</template>
<script>
import * as THREE from 'three';
// 导入控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// 引入房间环境,创建一个室内环境
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
// 导入性能监视器
import Stats from 'three/examples/jsm/libs/stats.module.js';
// 导入gltf载入库、模型加载器
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
// 引入模型解压器
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
//GUI界面
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';
import gsap from 'gsap';
export default {
	data() {
		return {
			container: null, //界面需要渲染的容器
			height: 0,//容器的高
			width: 0,//容器的宽
			scene: null,	// 场景对象
			camera: null, //相机对象
			renderer: null, //渲染器对象
			controller: null,	// 相机控件对象
			stats: null,// 性能监听器
			mixer: null,//动画混合器
			model: null,//导入的模型
			clock: new THREE.Clock(),// 创建一个clock对象,用于跟踪时间
			// 鼠标移动位置
			mouseX: 0,
			mouseY: 0,
			// 窗口位移
			windowHalfX: 0,
		};
	},
	mounted() {
		this.init()
		this.animate()  //如果引入了模型并存在动画,可在模型引入成功后加载动画
		window.addEventListener("resize", this.onWindowSize)
		window.addEventListener('mousemove', this.onDocumentMouseMove);
	},
	beforeUnmount() {
		console.log('beforeUnmount===============');
		// 组件销毁时置空,视具体情况自定义销毁,以下实例不完整
		this.container = null
		this.scene = null
		this.camera = null
		this.renderer = null
		this.controller = null
		this.stats = null
		this.mixer = null
		this.model = null//导入的模型
	},
	methods: {
		/**
		* @description 初始化
		 */
		init() {
			this.container = document.getElementById('container')
			this.width = this.container.clientWidth
			this.height = this.container.clientHeight
			this.windowHalfX = this.container.clientWidth / 2;
			this.windowHalfY = this.container.clientHeight / 2;
			this.setScene()
			this.setCamera()
			this.setRenderer()
			// this.setController()
			this.addHelper()
			// this.setPMREMGenerator()
			this.setLight()
			this.setMesh()
			this.addStatus()
		},
		/**
		 * @description 创建场景
		 */
		setScene() {
			// 创建场景对象Scene
			this.scene = new THREE.Scene()
			// 设置场景背景
			this.scene.background = new THREE.Color(0xffffff);
		},
		/**
		 * @description 创建相机
		*/
		setCamera() {
			// 第二参数就是 长度和宽度比 默认采用浏览器  返回以像素为单位的窗口的内部宽度和高度
			this.camera = new THREE.PerspectiveCamera(20, this.width / this.height, 1, 10000)
			// 设置相机位置
			this.camera.position.z = 1800;
			// 设置摄像头宽高比例
			this.camera.aspect = this.width / this.height;
			// 设置摄像头投影矩阵
			this.camera.updateProjectionMatrix();
			// 设置相机视线方向
			this.camera.lookAt(new THREE.Vector3(0, 0, 0))// 0, 0, 0 this.scene.position
			// 将相机加入场景
			this.scene.add(this.camera)
		},
		/**
		 * @description 创建渲染器
		 */
		setRenderer() {
			// 初始化渲染器
			this.renderer = new THREE.WebGLRenderer({
				antialias: true,// 设置抗锯齿
				logarithmicDepthBuffer: true,  // 是否使用对数深度缓存
			})
			// 设置渲染器宽高
			this.renderer.setSize(this.width, this.height);
			// 设置渲染器的像素比
			this.renderer.setPixelRatio(window.devicePixelRatio);
			// 是否需要对对象排序
			// this.renderer.sortObjects = false;
			// 将渲染器添加到页面
			this.container.appendChild(this.renderer.domElement);
		},
		/**
		 * @description 添加创建控制器
		 */
		setController() {
			this.controller = new OrbitControls(this.camera, this.renderer.domElement);
			// 控制缩放范围
			// this.controller.minDistance = 1;
			// this.controller.maxDistance = 5;
			//是否开启右键拖拽
			// this.controller.enablePan = false;
			// 阻尼(惯性)
			this.controller.enableDamping = true; //启用阻尼(惯性)
			this.controller.dampingFactor = 0.04; //阻尼惯性有多大
			// this.controller.autoRotate = true; //自动围绕目标旋转
			// this.controller.minAzimuthAngle = -Math.PI / 3; //能够水平旋转的角度下限。如果设置,其有效值范围为[-2 * Math.PI,2 * Math.PI],且旋转角度的上限和下限差值小于2 * Math.PI。默认值为无穷大。
			// this.controller.maxAzimuthAngle = Math.PI / 3;//水平旋转的角度上限,其有效值范围为[-2 * Math.PI,2 * Math.PI],默认值为无穷大
			// this.controller.minPolarAngle = 1; //能够垂直旋转的角度的下限,范围是0到Math.PI,其默认值为0。
			// this.controller.maxPolarAngle = Math.PI - 0.1; //能够垂直旋转的角度的上限,范围是0到Math.PI,其默认值为Math.PI。
			// 修改相机的lookAt是不会影响THREE.OrbitControls的target的
			// 由于设置了控制器,因此只能改变控制器的target以改变相机的lookAt方向
			this.controller.target.set(0, 0, 0); //控制器的焦点
		},
		/**
		 * @description 创建辅助坐标轴
		 */
		addHelper() {
			// 模拟相机视锥体的辅助对象
			let helper = new THREE.CameraHelper(this.camera);
			// this.scene.add(helper);
			//创建辅助坐标轴、轴辅助 (每一个轴的长度)
			let axisHelper = new THREE.AxesHelper(150);  // 红线是X轴,绿线是Y轴,蓝线是Z轴
			this.scene.add(axisHelper)
			// 坐标格辅助对象
			let gridHelper = new THREE.GridHelper(100, 30, 0x2C2C2C, 0x888888);
			this.scene.add(gridHelper);
		},
		/**
		 * @description 给场景添加环境光效果
		 */
		setPMREMGenerator() {
			// 预过滤的Mipmapped辐射环境贴图
			const pmremGenerator = new THREE.PMREMGenerator(this.renderer);
			this.scene.environment = pmremGenerator.fromScene(new RoomEnvironment(this.renderer), 0.04).texture;
		},
		/**
		 * @description 设置光源
		 */
		setLight() {
			// 环境光
			const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
			this.scene.add(ambientLight);
			// 平行光
			const directionalLight = new THREE.DirectionalLight(0xffffff, 3);
			directionalLight.position.set(1, 0, 0);
			this.scene.add(directionalLight);
		},
		/**
		 * @description 创建性能监听器
		*/
		addStatus() {
			// 创建一个性能监听器
			this.stats = new Stats();
			// 将性能监听器添加到容器中
			this.container.appendChild(this.stats.dom);
		},
		/**
		* @description 添加创建模型
		*/
		setMesh() {
			// 添加模型
			const radius = 200;//二十面体的半径
			const material = new THREE.MeshPhongMaterial({
				color: 0xffffff,
				flatShading: true,//材质是否使用平面着色进行渲染
				vertexColors: true,//是否使用顶点着色
				shininess: 0,//高亮的程度
			});
			// 生成一个半径为radius的二十面体的类
			const geometry1 = new THREE.IcosahedronGeometry(radius, 1);
			const wireframeMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, wireframe: true, transparent: true });//wireframe - 将几何体渲染为线框

			const count = geometry1.attributes.position.count;
			geometry1.setAttribute('color', new THREE.BufferAttribute(new Float32Array(count * 3), 3));

			const geometry2 = geometry1.clone();
			const geometry3 = geometry1.clone();

			const color = new THREE.Color();
			const positions1 = geometry1.attributes.position;
			const positions2 = geometry2.attributes.position;
			const positions3 = geometry3.attributes.position;
			const colors1 = geometry1.attributes.color;
			const colors2 = geometry2.attributes.color;
			const colors3 = geometry3.attributes.color;
			// 设置颜色
			for (let i = 0; i < count; i++) {
				color.setHSL((positions1.getY(i) / radius + 1) / 2, 1.0, 0.5, THREE.SRGBColorSpace);
				colors1.setXYZ(i, color.r, color.g, color.b);

				color.setHSL(0, (positions2.getY(i) / radius + 1) / 2, 0.5, THREE.SRGBColorSpace);
				colors2.setXYZ(i, color.r, color.g, color.b);

				color.setRGB(1, 0.8 - (positions3.getY(i) / radius + 1) / 2, 0, THREE.SRGBColorSpace);
				colors3.setXYZ(i, color.r, color.g, color.b);
			}
			// 左边
			let mesh = new THREE.Mesh(geometry1, material)//二十面体
			let wireframe = new THREE.Mesh(geometry1, wireframeMaterial);//二十面体线框。同一几何体下,由于材质不同,形成几何线框
			mesh.add(wireframe);//为二十面体添加线框
			mesh.position.x = - 400;
			mesh.rotation.x = - 1.87;
			this.scene.add(mesh);
			// 右边
			mesh = new THREE.Mesh(geometry2, material);
			wireframe = new THREE.Mesh(geometry2, wireframeMaterial);
			mesh.add(wireframe);
			mesh.position.x = 400;
			this.scene.add(mesh);
			// 中间
			mesh = new THREE.Mesh(geometry3, material);
			wireframe = new THREE.Mesh(geometry3, wireframeMaterial);
			mesh.add(wireframe);
			this.scene.add(mesh);


			// shadow
			const canvas = document.createElement('canvas');
			canvas.width = 128;
			canvas.height = 128;

			const context = canvas.getContext('2d');
			const gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2);
			gradient.addColorStop(0.1, 'rgba(210,210,210,1)');
			gradient.addColorStop(1, 'rgba(255,255,255,1)');

			context.fillStyle = gradient;
			context.fillRect(0, 0, canvas.width, canvas.height);

			const shadowTexture = new THREE.CanvasTexture(canvas);// 从Canvas元素中创建纹理贴图

			const shadowMaterial = new THREE.MeshBasicMaterial({ map: shadowTexture });
			const shadowGeo = new THREE.PlaneGeometry(300, 300, 1, 1);
			let shadowMesh;

			shadowMesh = new THREE.Mesh(shadowGeo, shadowMaterial);
			shadowMesh.position.y = - 250;
			shadowMesh.rotation.x = - Math.PI / 2;
			this.scene.add(shadowMesh);

			shadowMesh = new THREE.Mesh(shadowGeo, shadowMaterial);
			shadowMesh.position.y = - 250;
			shadowMesh.position.x = - 400;
			shadowMesh.rotation.x = - Math.PI / 2;
			this.scene.add(shadowMesh);

			shadowMesh = new THREE.Mesh(shadowGeo, shadowMaterial);
			shadowMesh.position.y = - 250;
			shadowMesh.position.x = 400;
			shadowMesh.rotation.x = - Math.PI / 2;
			this.scene.add(shadowMesh);
		},
		/**
		 * @description 监听屏幕的大小改变,修改渲染器的宽高,相机的比例
		*/
		// 窗口变化
		onWindowSize() {
			this.width = this.container.clientWidth
			this.height = this.container.clientHeight
			this.windowHalfX = this.container.clientWidth / 2;
			this.windowHalfY = this.container.clientHeight / 2;
			// 更新摄像头
			this.camera.aspect = this.width / this.height;
			// 更新摄像机的投影矩阵
			this.camera.updateProjectionMatrix();
			//更新渲染器
			this.renderer.setSize(this.width, this.height);
			// 设置渲染器的像素比
			this.renderer.setPixelRatio(window.devicePixelRatio)
		},
		/**
		* @description 监听 mousemove 窗口事件
		*/
		onDocumentMouseMove(event) {
			this.mouseX = (event.clientX - this.windowHalfX)
			this.mouseY = (event.clientY - this.windowHalfY)
		},
		/**
		* @description 动画执行函数
		*/
		animate() {
			// camera聚焦(跟随鼠标位置移动)
			this.camera.position.x += (this.mouseX - this.camera.position.x) * 0.05;
			this.camera.position.y += (- this.mouseY - this.camera.position.y) * 0.05;
			this.camera.lookAt(this.scene.position);

			const delta = this.clock.getDelta();
			// mixer 动画更新
			if (this.mixer) {
				this.mixer.update(delta);
			}
			// 引擎自动更新渲染器
			requestAnimationFrame(this.animate);
			//update()函数内会执行camera.lookAt(x, y, z)
			// this.controller.update(delta);
			// 更新性能监听器
			this.stats.update();
			// 重新渲染场景
			this.renderer.render(this.scene, this.camera);
		},
	},
};
</script>
<style>
#container {
	position: absolute;
	width: 100%;
	height: 100%;
}
</style>


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值