我正在尝试为加载的 .stl 3D 对象添加交互式鼠标控制。我的困难在于集成鼠标控制代码,而不是查找示例或显示对象。下面是我正在使用的。我的偏好是使用鼠标事件控制相机位置(而不是抓住对象上的定义点),这样看起来我正在用鼠标旋转对象并用滚轮放大和缩小。
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - STL</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000000;
margin: 0px;
overflow: hidden;
}
a { color: skyblue }
</style>
</head>
<body>
<script src="https://raw.github.com/mrdoob/three.js/master/build/three.min.js"></script>
<script src="https://raw.github.com/mrdoob/three.js/master/examples/js/loaders/STLLoader.js"></script>
<script src="https://raw.github.com/mrdoob/three.js/master/examples/js/controls/TrackballControls.js"></script>
<script>
var container, camera, scene, renderer;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera(
35, // field of view
window.innerWidth / window.innerHeight, // aspect ratio
1 , // distance to nearest side of rendered space
10000 // distance to farthest side of rendered space
);
camera.position.set( 3, -3, -3 ); // initial camera position x,y,z coordinates
scene = new THREE.Scene();
// object
var loader = new THREE.STLLoader();
loader.addEventListener( 'load', function ( event ) {
var geometry = event.content;
var material = new THREE.MeshLambertMaterial( { ambient: 0xff5533, color: 0xff5533 } ); //color: object hexadecimal color after the 0x
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
} );
loader.load( 'slotted_disk.stl' ); // from https://raw.github.com/mrdoob/three.js/dev/examples/models/stl/slotted_disk.stl
// lights
scene.add( new THREE.AmbientLight( 0x222222 ) );
var directionalLight = new THREE.DirectionalLight( 0xffffff, 1 );
directionalLight.position = camera.position;
scene.add( directionalLight );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
}
function addLight( x, y, z, color, intensity ) {
var directionalLight = new THREE.DirectionalLight( color, intensity );
directionalLight.position.set( x, y, z )
scene.add( directionalLight );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
//var timer = Date.now() * 0.0005; // optional for auto rotation
//camera.position.x = Math.sin ( timer ) * 5; // optional for auto rotation
//camera.position.z = Math.cos( timer ) * 5; // optional for auto rotation
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
</body>