原理:利用 CSS3DObject 将二维物体转为 threejs 可以识别的 3d 物品,然后利用 CSS3DRenderer 将其渲染到页面,以下注释中步骤 2,3,4 最为重要。
使用场景:常常用来制作全景图效果,如3d在线看房。只需要6张图片构成一个长方体就可以利用 CSS3DRenderer 渲染出一个立体全景图效果
<!DOCTYPE html>
<html>
<head>
<title>three.js css3d - panorama</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info"><a href="http://threejs.org" target="_blank" rel="noopener">three.js css3d</a> - panorama demo. cubemap
by <a href="http://www.humus.name/index.php?page=Textures" target="_blank" rel="noopener">Humus</a>.</div>
<script type="module">
import * as THREE from '../build/three.module.js';
import { CSS3DRenderer, CSS3DObject } from './jsm/renderers/CSS3DRenderer.js';
import { OrbitControls } from './jsm/controls/OrbitControls.js';
var camera, scene, renderer,controls;
init();
animate();
function init() {
// 1、创建场景,相机
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 );
camera.lookAt(0,100,100)
scene = new THREE.Scene();
var sides = [
{
url: 'textures/cube/Bridge2/posx.jpg',
position: [ - 512, 0, 0 ],
rotation: [ 0, Math.PI / 2, 0 ]
},
{
url: 'textures/cube/Bridge2/negx.jpg',
position: [ 512, 0, 0 ],
rotation: [ 0, - Math.PI / 2, 0 ]
},
{
url: 'textures/cube/Bridge2/posy.jpg',
position: [ 0, 512, 0 ],
rotation: [ Math.PI / 2, 0, Math.PI ]
},
{
url: 'textures/cube/Bridge2/negy.jpg',
position: [ 0, - 512, 0 ],
rotation: [ - Math.PI / 2, 0, Math.PI ]
},
{
url: 'textures/cube/Bridge2/posz.jpg',
position: [ 0, 0, 512 ],
rotation: [ 0, Math.PI, 0 ]
},
{
url: 'textures/cube/Bridge2/negz.jpg',
position: [ 0, 0, - 512 ],
rotation: [ 0, 0, 0 ]
}
];
for ( var i = 0; i < sides.length; i ++ ) {
var side = sides[ i ];
// 2、创建 img 元素
var element = document.createElement( 'img' );
element.width = 1026; // 2 pixels extra to close the gap.
element.src = side.url;
// 3、利用 CSS3DObject 将 img 元素转为 3d 物体
var object = new CSS3DObject( element );
object.position.fromArray( side.position );
object.rotation.fromArray( side.rotation );
scene.add( object );
}
// 4、创建渲染器
renderer = new CSS3DRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// 5、创建交互控制器
controls = new OrbitControls( camera, renderer.domElement );
controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
controls.dampingFactor = 0.25;
controls.screenSpacePanning = false;
controls.minDistance = 100;
controls.maxDistance = 1500;
controls.maxPolarAngle = Math.PI / 2;
}
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
</script>
</body>
</html>
效果:
6张图片合成一个全景图
网友评论