picking-raycaster.html 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Picking - RayCaster</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../../build/three.module.js"
  27. }
  28. }
  29. </script>
  30. <script type="module">
  31. import * as THREE from 'three';
  32. function main() {
  33. const canvas = document.querySelector( '#c' );
  34. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  35. const fov = 60;
  36. const aspect = 2; // the canvas default
  37. const near = 0.1;
  38. const far = 200;
  39. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  40. camera.position.z = 30;
  41. const scene = new THREE.Scene();
  42. scene.background = new THREE.Color( 'white' );
  43. // put the camera on a pole (parent it to an object)
  44. // so we can spin the pole to move the camera around the scene
  45. const cameraPole = new THREE.Object3D();
  46. scene.add( cameraPole );
  47. cameraPole.add( camera );
  48. {
  49. const color = 0xFFFFFF;
  50. const intensity = 3;
  51. const light = new THREE.DirectionalLight( color, intensity );
  52. light.position.set( - 1, 2, 4 );
  53. camera.add( light );
  54. }
  55. const boxWidth = 1;
  56. const boxHeight = 1;
  57. const boxDepth = 1;
  58. const geometry = new THREE.BoxGeometry( boxWidth, boxHeight, boxDepth );
  59. function rand( min, max ) {
  60. if ( max === undefined ) {
  61. max = min;
  62. min = 0;
  63. }
  64. return min + ( max - min ) * Math.random();
  65. }
  66. function randomColor() {
  67. return `hsl(${rand( 360 ) | 0}, ${rand( 50, 100 ) | 0}%, 50%)`;
  68. }
  69. const numObjects = 100;
  70. for ( let i = 0; i < numObjects; ++ i ) {
  71. const material = new THREE.MeshPhongMaterial( {
  72. color: randomColor(),
  73. } );
  74. const cube = new THREE.Mesh( geometry, material );
  75. scene.add( cube );
  76. cube.position.set( rand( - 20, 20 ), rand( - 20, 20 ), rand( - 20, 20 ) );
  77. cube.rotation.set( rand( Math.PI ), rand( Math.PI ), 0 );
  78. cube.scale.set( rand( 3, 6 ), rand( 3, 6 ), rand( 3, 6 ) );
  79. }
  80. function resizeRendererToDisplaySize( renderer ) {
  81. const canvas = renderer.domElement;
  82. const width = canvas.clientWidth;
  83. const height = canvas.clientHeight;
  84. const needResize = canvas.width !== width || canvas.height !== height;
  85. if ( needResize ) {
  86. renderer.setSize( width, height, false );
  87. }
  88. return needResize;
  89. }
  90. class PickHelper {
  91. constructor() {
  92. this.raycaster = new THREE.Raycaster();
  93. this.pickedObject = null;
  94. this.pickedObjectSavedColor = 0;
  95. }
  96. pick( normalizedPosition, scene, camera, time ) {
  97. // restore the color if there is a picked object
  98. if ( this.pickedObject ) {
  99. this.pickedObject.material.emissive.setHex( this.pickedObjectSavedColor );
  100. this.pickedObject = undefined;
  101. }
  102. // cast a ray through the frustum
  103. this.raycaster.setFromCamera( normalizedPosition, camera );
  104. // get the list of objects the ray intersected
  105. const intersectedObjects = this.raycaster.intersectObjects( scene.children );
  106. if ( intersectedObjects.length ) {
  107. // pick the first object. It's the closest one
  108. this.pickedObject = intersectedObjects[ 0 ].object;
  109. // save its color
  110. this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
  111. // set its emissive color to flashing red/yellow
  112. this.pickedObject.material.emissive.setHex( ( time * 8 ) % 2 > 1 ? 0xFFFF00 : 0xFF0000 );
  113. }
  114. }
  115. }
  116. const pickPosition = { x: 0, y: 0 };
  117. const pickHelper = new PickHelper();
  118. clearPickPosition();
  119. function render( time ) {
  120. time *= 0.001; // convert to seconds;
  121. if ( resizeRendererToDisplaySize( renderer ) ) {
  122. const canvas = renderer.domElement;
  123. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  124. camera.updateProjectionMatrix();
  125. }
  126. cameraPole.rotation.y = time * .1;
  127. pickHelper.pick( pickPosition, scene, camera, time );
  128. renderer.render( scene, camera );
  129. requestAnimationFrame( render );
  130. }
  131. requestAnimationFrame( render );
  132. function getCanvasRelativePosition( event ) {
  133. const rect = canvas.getBoundingClientRect();
  134. return {
  135. x: ( event.clientX - rect.left ) * canvas.width / rect.width,
  136. y: ( event.clientY - rect.top ) * canvas.height / rect.height,
  137. };
  138. }
  139. function setPickPosition( event ) {
  140. const pos = getCanvasRelativePosition( event );
  141. pickPosition.x = ( pos.x / canvas.width ) * 2 - 1;
  142. pickPosition.y = ( pos.y / canvas.height ) * - 2 + 1; // note we flip Y
  143. }
  144. function clearPickPosition() {
  145. // unlike the mouse which always has a position
  146. // if the user stops touching the screen we want
  147. // to stop picking. For now we just pick a value
  148. // unlikely to pick something
  149. pickPosition.x = - 100000;
  150. pickPosition.y = - 100000;
  151. }
  152. window.addEventListener( 'mousemove', setPickPosition );
  153. window.addEventListener( 'mouseout', clearPickPosition );
  154. window.addEventListener( 'mouseleave', clearPickPosition );
  155. window.addEventListener( 'touchstart', ( event ) => {
  156. // prevent the window from scrolling
  157. event.preventDefault();
  158. setPickPosition( event.touches[ 0 ] );
  159. }, { passive: false } );
  160. window.addEventListener( 'touchmove', ( event ) => {
  161. setPickPosition( event.touches[ 0 ] );
  162. } );
  163. window.addEventListener( 'touchend', clearPickPosition );
  164. }
  165. main();
  166. </script>
  167. </html>