[英]How to draw a geometry shape exactly where mouse is clicked in ThreeJS
I am trying to draw a circle exactly where mouse is clicked, but circle is drawn not at exact position.我正在尝试在单击鼠标的位置准确地绘制一个圆圈,但在 position 处绘制的圆圈并不准确。 Please let me know what needs to be corrected in the code:
请让我知道代码中需要更正的内容:
var camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 0, 0, 1000 );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
function onDocumentMouseDown( event ) {
event.preventDefault();
if( event.which == 1) { // left mouse click
// x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
// y = - ( event.clientY / renderer.domElement.clientWidth ) * 2 + 1;
var x = event.clientX; // x coordinate of a mouse pointer
var y = event.clientY; // y coordinate of a mouse pointer
var rect = event.target.getBoundingClientRect();
x = ((x - rect.left) - window.innerWidth/2)/(window.innerWidth/2);
y = (window.innerHeight/2 - (y - rect.top))/(window.innerHeight/2);
var geometry = new THREE.CircleGeometry( 20, 32 );
var material = new THREE.MeshBasicMaterial( { color: 0x65A8FF } );
circle = new THREE.Mesh( geometry, material );
//circle.position.x = x*window.innerWidth*1.23;
//circle.position.y = y*765;
circle.position.x = x*window.innerWidth;
circle.position.y = y*window.innerHeight;
scene.add( circle );
}
}
The problem with your approach is that it's assuming 3D xy
coordinates are connected to pixel coordinates without taking the camera's perspective or depth into account.您的方法的问题在于它假设 3D
xy
坐标连接到像素坐标,而不考虑相机的视角或深度。 With a perspective camera, the deeper the point goes, the greater its x, y coords will be.使用透视相机,点越深,它的 x、y 坐标就越大。 You need to set a depth (z) for the points to stop at.
您需要为要停止的点设置深度 (z)。 Additionally, if your camera moves or rotates, your
X, Y
coordinates will not work.此外,如果您的相机移动或旋转,您的
X, Y
坐标将不起作用。
I recommend you use a THREE.Raycaster
, which performs all those camera projection calculations for you (the docs have an example of its usage at the top of the page).我建议您使用
THREE.Raycaster
,它会为您执行所有这些相机投影计算(文档在页面顶部有一个使用示例)。 You can see that approach in action in this example .您可以在此示例中看到该方法的实际效果。
The way it works is:它的工作方式是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.