我一直在玩 Three.js 一段时间,我目前处理鼠标拖动的方式与 three.js 的可拖动立方体示例相同,使用轨迹球控件来操作相机,但是这些控件似乎都假设我将整个浏览器窗口用于我的应用程序。
有没有办法将这些鼠标控件缩放(和限制)到我的画布?
编辑:这是一个显示拖动对象的鼠标事件的代码示例(它实际上与 three.js 的示例目录中提供的示例几乎相同,但我应用了 uhura 的代码)
`//Called when cursor is moved, drags object if one is selected
function onDocumentMouseMove( event ) {
event.preventDefault();
//mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
//mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
mouse.x = cursorPositionInCanvas( renderer.domElement, event )[0];
mouse.y = cursorPositionInCanvas( renderer.domElement, event )[1];
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
projector.unprojectVector( vector, camera );
var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
if ( SELECTED ) {
var intersects = raycaster.intersectObject( plane );
SELECTED.position.copy( intersects[ 0 ].point.sub( offset ) );
return;
}
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
if ( INTERSECTED != intersects[ 0 ].object ) {
INTERSECTED = intersects[ 0 ].object;
plane.position.copy( INTERSECTED.position );
plane.lookAt( camera.position );
}
}
else {
INTERSECTED = null;
}
}
//Called when user clicks, selects object if mouse is over it and disables trackball controls
function onDocumentMouseDown( event ) {
event.preventDefault();
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
projector.unprojectVector( vector, camera );
var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
controls.enabled = false;
SELECTED = intersects[ 0 ].object;
var intersects = raycaster.intersectObject( plane );
offset.copy( intersects[ 0 ].point ).sub( plane.position );
}
}
//Called when user releases mouse button, deselects any selected objects and re-enables trackball controls
function onDocumentMouseUp( event ) {
event.preventDefault();
controls.enabled = true;
if ( INTERSECTED ) {
plane.position.copy( INTERSECTED.position );
SELECTED = null;
}
}
function cursorPositionInCanvas(canvas, event) {
var x, y;
canoffset = $(canvas).offset();
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;
return [x,y];
}`