<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="./main.js"></script>
</body>
</html>
index.html
main.js
package.json
现在支持上传本地图片了!
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// 引入gltf模型加载库GLTFLoader.js
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const R = 100; //圆弧半径
const N = 50; //分段数量
const sp = 2 * Math.PI / N;//两个相邻点间隔弧度
const arr = [];
// 批量生成圆弧上的顶点数据
for (let i = 0; i < N; i++) {
const angle = sp * i;//当前点弧度
// 以坐标原点为中心,在XOY平面上生成圆弧上的顶点数据
const x = R * Math.cos(angle);
const y = R * Math.sin(angle);
arr.push(x, y, 0);
}
//类型数组创建顶点数据
const vertices = new Float32Array(arr);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 3000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
const attribue = new THREE.BufferAttribute(vertices, 3); // 创建属性缓冲区对象
const geometry = new THREE.BufferGeometry();
const material = new THREE.LineBasicMaterial({
color: 0xff0000
});
const line = new THREE.LineLoop(geometry, material);
const axesHelper = new THREE.AxesHelper(150);
const ambientLight = new THREE.AmbientLight(0x404040, 2); // 添加环境光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1); // 添加方向光
const pointLight = new THREE.PointLight(0xff0000, 2, 10); // 添加点光源,红色的点光源
const controls = new OrbitControls(camera, renderer.domElement); // 添加轨道控制器
// 设置几何体attributes属性的位置属性
geometry.attributes.position = attribue;
// console.log(geometry.attributes.position)
directionalLight.position.set(5, 5, 5).normalize();
directionalLight.castShadow = true; // 方向光投射阴影
pointLight.position.set(2, 2, 2);
pointLight.castShadow = true; // 点光源投射阴影
controls.enableDamping = true; // 启用阻尼效果
controls.dampingFactor = 0.05; // 阻尼系数
scene.add(line);
scene.add(axesHelper);
scene.add(directionalLight);
scene.add(ambientLight);
scene.add(pointLight);
// 设置相机位置
camera.position.set(300, 100, 600);
camera.lookAt(line.position);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true; // 启用阴影
renderer.setClearColor(0x444444, 1);
document.body.appendChild(renderer.domElement);
// 动画循环
const animate = () => {
requestAnimationFrame(animate);
// 渲染场景
renderer.render(scene, camera);
};
// 启动动画
animate();
// 窗口大小调整时更新相机和渲染器
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
{
"dependencies": {
"three": "0.173.0"
}
}
预览