1.创建一个简单的three场景

105 阅读1分钟

html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./js/index1.js"></script>
</body>
</html>

js部分

import * as THREE from 'three'
//创建一个场景
const scene = new THREE.Scene();
//创建一个相机
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
//创建渲染器
const renderer = new THREE.WebGLRenderer();
//设置渲染器背景色
renderer.setClearColor(0xEEEEEE);
//设置场景渲染的尺寸
renderer.setSize(window.innerWidth, window.innerHeight);
//创建坐标轴
const axes = new THREE.AxesHelper(20);
//把坐标轴添加到场景重
scene.add(axes)
//创建一个平面(宽60,高20)
const planeGeometry = new THREE.PlaneGeometry(60, 20);
//设置平面的材质 颜色为0xcccccc
const planeMaterial = new THREE.MeshBasicMaterial({ color: 0xcccccc });
//把平面和材质合并到网格中
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
//把plane网格对象旋转90度
plane.rotation.x = -0.5 * Math.PI;
//设置plane对象的位置
plane.position.x = 15;

plane.position.y = 0;

plane.position.z = 0;
//把plane对象放入场景中
scene.add(plane);
//创建一个立方体
const cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
//创建立方体的材质
const cubeMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
//把立方体和材质放入网格中
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
//设定位置
cube.position.x = -4;

cube.position.y = 3;

cube.position.z = 0;
//把cube对象放入场景中
scene.add(cube);
//创建一个球体
const sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
//创建球体的材质
const sphereMaterial = new THREE.MeshBasicMaterial({ color: 0x7777ff, wireframe: true })
//把球体和材质放入网格对象中
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial)
//设置位置
sphere.position.x = 20;

sphere.position.y = 4;

sphere.position.z = 2;
//把sphere放入场景中
scene.add(sphere);
//设置相机的位置 悬挂在场景的上方
camera.position.x = -30;
camera.position.y = 40;
camera.position.z = 30;
//将相机指向场景的中心
camera.lookAt(scene.position);
//把渲染器挂载到页面中
document.body.appendChild(renderer.domElement);
//告诉渲染器,提供相机来渲染场景
renderer.render(scene, camera);