<!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 = 80; // 圆弧半径
const H = 200; // 直线部分高度
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 line1 = new THREE.LineCurve(new THREE.Vector2(R, H), new THREE.Vector2(R, 0));
const line2 = new THREE.LineCurve(new THREE.Vector2(-R, H), new THREE.Vector2(-R, 0));
const arc = new THREE.ArcCurve(0, 0, R, 0, Math.PI, true);
const curvePath = new THREE.CurvePath();
curvePath.curves.push(line1, arc, line2); // CurvePath创建一个组合曲线对象并进行拼接
// 点模型可视化组合曲线
const points = curvePath.getPoints(100);
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({color: 0xff0000});
const curveLine = new THREE.Line(geometry, material);
const axesHelper = new THREE.AxesHelper(100);
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); // 添加轨道控制器
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(curveLine);
scene.add(axesHelper);
scene.add(directionalLight);
scene.add(ambientLight);
scene.add(pointLight);
// 设置相机位置
camera.position.set(200, 200, 200);
camera.lookAt(0, 0, 0);
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"
}
}
预览