The short answer is you have to take into consideration the offset
of the canvas.
The long answer depends on how your code is written, so I'll give you two answers, which should cover the bases.
There are a lot of possible combinations, so you may have to experiment. Also, different browsers may act differently.
Assume your HTML is something like this:
#canvas {
width: 200px;
height: 200px;
margin: 100px;
padding: 0px;
position: static; /* fixed or static */
top: 100px;
left: 100px;
}
<body>
<div id="canvas">
</body>
Your JS is something like this:
var CANVAS_WIDTH = 200,
CANVAS_HEIGHT = 200;
var container = document.getElementById( 'canvas' );
document.body.appendChild( container );
renderer = new THREE.WebGLRenderer();
renderer.setSize( CANVAS_WIDTH, CANVAS_HEIGHT );
container.appendChild( renderer.domElement );
Method 1 For the following method to work correctly, set the canvas position static; margin > 0 and padding > 0 are OK
mouse.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / renderer.domElement.clientHeight ) * 2 + 1;
Method 2 For this alternate method, set the canvas position fixed; set top > 0, set left > 0; padding must be 0; margin > 0 is OK
mouse.x = ( ( event.clientX - container.offsetLeft ) / container.clientWidth ) * 2 - 1;
mouse.y = - ( ( event.clientY - container.offsetTop ) / container.clientHeight ) * 2 + 1;
Here is a Fiddle if you want to experiment: http://jsfiddle.net/cn7ecoaa/
EDIT: Fiddle updated to three.js r.84
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…