picking-raycaster.html 5.6 KB

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