threejs

npm create vite@latest
npm i three@0.157.0 -S

index.js

// 引入threejs
import * as THREE from "three";

import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

// 创建一个三维场景scene
const scene = new THREE.Scene();

// 给三维场景添加物体

// 定义一个几何体 长方体 长宽高都是100
const geometry = new THREE.BoxGeometry(100, 100, 100);

// 创建一个材质对象
const material = new THREE.MeshBasicMaterial({
  color: 0xff0000,
});

// 创建一个网格模型:表示生活中的物体
const mesh = new THREE.Mesh(geometry, material);

// 设置物体的位置
mesh.position.set(0, 10, 0);

// 把mesh添加到场景中
scene.add(mesh);

// 定义相机输出画布的尺寸(px)
const width = window.innerWidth;
const height = window.innerHeight;

// 设置相机的四个参数

// 创建一个透视投影相机对象
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);

// 设置相机的位置
camera.position.set(200, 200, 200);

// 定义相机的视线   观察目标点的坐标
// camera.lookAt(0, 0, 0)  // 坐标原点
// camera.lookAt(0, 10, 0)  // y轴上
camera.lookAt(mesh.position); // 指向网格模型mesh

// 创建一个WebGL渲染器
const renderer = new THREE.WebGLRenderer();

// canvas画布的宽高
renderer.setSize(width, height);

// 执行渲染动作
renderer.render(scene, camera);

// 把渲染结果添加到网页页面上
document.body.appendChild(renderer.domElement);

// document.getElementById('webgl').appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement);
// 如果OrbitControls改变了相机参数,重新调用渲染器渲染三维场景
controls.addEventListener("change", function (params) {
  // 执行渲染动作
  renderer.render(scene, camera);
  console.log(camera.position);
});

运行结果,可以使用鼠标放大缩小,按住鼠标左键可以调转方向 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值