picking-raycaster.html 5.6 KB

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