记录:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>three.js css2d - label</title>
<link type="text/css" rel="stylesheet" href="main.css">
<style>
body{
background-color: #fff!important;
}
</style>
</head>
<body>
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from './jsm/controls/OrbitControls.js';
let camera, scene, renderer;
const textureLoader = new THREE.TextureLoader();
init();
animate();
function init() {
// 场景
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff); // 设置场景背景颜色
// 相机 (fov, aspect, near, far)
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 0.1, 200 );
camera.position.set( 10, 5, 20 );
// 创建环境光
const light = new THREE.AmbientLight(0xffffff, 1)
scene.add(light)
// 渲染器
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//辅助器3维坐标
const axesHelper = new THREE.AxesHelper( 5 );
axesHelper.layers.enableAll();
scene.add( axesHelper );
// 物体
const cubeGeometry = new THREE.BoxGeometry(1,1,1)
const cubeMaterial = new THREE.MeshBasicMaterial({color: 0xffff00})
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
scene.add( cube );
// 控制器
const controls = new OrbitControls( camera, renderer.domElement );
controls.minDistance = 5;
controls.maxDistance = 100;
// 平行光源
// const dirLight = new THREE.DirectionalLight( 0xffffff );
// dirLight.position.set( 2, 2, 2 );
// scene.add( dirLight );
// // 平行光源辅助线
// const directionalLightHelper = new THREE.DirectionalLightHelper(dirLight, .5)
// directionalLightHelper.visible = true
// scene.add(directionalLightHelper)
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
// 持续渲染
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
</script>
</body>
</html>
基础3D页面,场景,光源,相机,渲染器等的基础配置。