帮我用threejs写一个完整的代码,画一个窗户,视角可以自由切换和固定,窗户大小可以自己调节...
时间: 2024-03-06 07:49:34 浏览: 239
好的,以下是一个简单的Three.js代码示例,可以画一个窗户,并且可以通过鼠标进行视角切换。同时,你也可以通过修改代码自己调节窗户大小:
```html
<!DOCTYPE html>
<html>
<head>
<title>Three.js Window</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
let camera, scene, renderer;
let windowWidth = 2, windowHeight = 2;
init();
animate();
function init() {
// 创建相机
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 2;
// 创建场景
scene = new THREE.Scene();
// 创建窗户
const geometry = new THREE.PlaneGeometry( windowWidth, windowHeight );
const material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
const window = new THREE.Mesh( geometry, material );
scene.add( window );
// 创建渲染器
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// 添加事件监听器
window.addEventListener( 'resize', onWindowResize );
document.addEventListener( 'mousemove', onDocumentMouseMove );
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
const mouseX = event.clientX / window.innerWidth * 2 - 1;
const mouseY = - event.clientY / window.innerHeight * 2 + 1;
camera.position.x = mouseX * 0.1;
camera.position.y = mouseY * 0.1;
camera.lookAt( 0, 0, 0 );
}
</script>
</body>
</html>
```
这段代码创建了一个窗户的平面,并使用了简单的材质。你可以通过修改 `windowWidth` 和 `windowHeight` 变量来调整窗户大小。同时,你也可以通过修改 `onDocumentMouseMove` 函数来实现自由切换视角或者固定视角。
阅读全文