threejs基本知识1

本文详细介绍了如何使用THREE.js在WebGL环境中创建场景、设置相机、光照及基础几何体,包括位置、旋转和缩放操作,以及辅助工具的使用。通过实例演示了如何构建一个带有坐标轴和刷新帧的交互式3D立方体。
摘要由CSDN通过智能技术生成

threejs基本知识1

场景、相机、渲染器、灯光、基础几何体、基础材质、位置变化、旋转、缩放、坐标轴线辅助器、刷新帧辅助器、鼠标控制辅助器
	  // 浏览器宽度
	  let w = window.innerWidth; 
	  
	  // 浏览器高度
      let h = window.innerHeight; 
      
      // 创建场景
      const scene = new THREE.Scene(); 
      
	  // 创建相机 (视角 宽高比 最近距离 最远距离)
      const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 1000); 
      // 相机位置
      camera.position.set(1, 1, 5); 
      // 相机视角
      camera.lookAt(0, 0, 0); 
	
	  // 创建基础几何体(骨架) 长宽高
      const geometry = new THREE.BoxGeometry(1, 1, 1); 
	  // 创建材质(皮肤)
      const material = new THREE.MeshBasicMaterial({ color: "blue" }); 
	  // 创建物体(骨架+皮肤)
      const cube = new THREE.Mesh(geometry, material); 

      // Position 位置变换
      // cube.position.x = 1
      // cube.position.y = 1
      // cube.position.z = 1
      // cube.position.set(1, 1, 1);

      // Rotation 旋转
      // cube.rotation.z = 45 / 180 * Math.PI
      // cube.rotation.set(
      //   (45 / 180) * Math.PI,
      //   (45 / 180) * Math.PI,
      //   (45 / 180) * Math.PI
      // );

      // scale 缩放(2倍)
      // cube.scale.x = 2
      // cube.scale.set(2, 2, 2); 
		
	  // 创建灯光
      const light = new THREE.AmbientLight(); 
		
	  // 坐标轴辅助器
      const axes = new THREE.AxesHelper(10, 10, 10); 
		
	  // 物体放在场景中
      scene.add(cube); 
      // 灯光放入场景中
      scene.add(light); 
      // 坐标轴辅助器
      scene.add(axes); 
      
	  // 创建渲染器
      const renderer = new THREE.WebGLRenderer();
      // 渲染器尺寸
      renderer.setSize(w, h); 
      // 场景和相机放在渲染器中
      renderer.render(scene, camera); 
      // 渲染器需要放入html元素中
	  document.getElementById("box-container").append(renderer.domElement);
	  
	  // 刷新帧辅助器
      const stats = new Stats(); 
	  document.getElementById("box-container").append(stats.domElement);
	  
	  // 控制辅助器(鼠标滚动缩放、右击平移、左击旋转)
      const orbitControls = new OrbitControls(camera, renderer.domElement); 
		
	  // 帧率刷新辅助器
      const clock = new THREE.Clock();
      function render() {
      // 在不同频率下稳定增长的值
        const time = clock.getElapsedTime(); 
        // 方形box稳定值旋转
        cube.rotation.z = time;
        // 场景和相机放在渲染器中
        renderer.render(scene, camera); 
        // 与浏览器刷新帧率同步(性能优于定时器)
        stats.update();
        orbitControls.update();
        requestAnimationFrame(render);
      }
      render();
   // 自适应窗口大小变化 从而更新画布
	 window.addEventListener("resize", () => {
        w = window.innerWidth;
        h = window.innerHeight;
        camera.aspect = w / h;
        camera.updateProjectionMatrix();
        renderer.setSize(w, h);
      });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值