picking-raycaster-transparency.html 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 w/Transparency</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 loader = new THREE.TextureLoader();
  74. const texture = loader.load( 'resources/images/frame.png' );
  75. const numObjects = 100;
  76. for ( let i = 0; i < numObjects; ++ i ) {
  77. const material = new THREE.MeshPhongMaterial( {
  78. color: randomColor(),
  79. map: texture,
  80. transparent: true,
  81. side: THREE.DoubleSide,
  82. alphaTest: 0.1,
  83. } );
  84. const cube = new THREE.Mesh( geometry, material );
  85. scene.add( cube );
  86. cube.position.set( rand( - 20, 20 ), rand( - 20, 20 ), rand( - 20, 20 ) );
  87. cube.rotation.set( rand( Math.PI ), rand( Math.PI ), 0 );
  88. cube.scale.set( rand( 3, 6 ), rand( 3, 6 ), rand( 3, 6 ) );
  89. }
  90. function resizeRendererToDisplaySize( renderer ) {
  91. const canvas = renderer.domElement;
  92. const width = canvas.clientWidth;
  93. const height = canvas.clientHeight;
  94. const needResize = canvas.width !== width || canvas.height !== height;
  95. if ( needResize ) {
  96. renderer.setSize( width, height, false );
  97. }
  98. return needResize;
  99. }
  100. class PickHelper {
  101. constructor() {
  102. this.raycaster = new THREE.Raycaster();
  103. this.pickedObject = null;
  104. this.pickedObjectSavedColor = 0;
  105. }
  106. pick( normalizedPosition, scene, camera, time ) {
  107. // restore the color if there is a picked object
  108. if ( this.pickedObject ) {
  109. this.pickedObject.material.emissive.setHex( this.pickedObjectSavedColor );
  110. this.pickedObject = undefined;
  111. }
  112. // cast a ray through the frustum
  113. this.raycaster.setFromCamera( normalizedPosition, camera );
  114. // get the list of objects the ray intersected
  115. const intersectedObjects = this.raycaster.intersectObjects( scene.children );
  116. if ( intersectedObjects.length ) {
  117. // pick the first object. It's the closest one
  118. this.pickedObject = intersectedObjects[ 0 ].object;
  119. // save its color
  120. this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
  121. // set its emissive color to flashing red/yellow
  122. this.pickedObject.material.emissive.setHex( ( time * 8 ) % 2 > 1 ? 0xFFFF00 : 0xFF0000 );
  123. }
  124. }
  125. }
  126. const pickPosition = { x: 0, y: 0 };
  127. const pickHelper = new PickHelper();
  128. clearPickPosition();
  129. function render( time ) {
  130. time *= 0.001; // convert to seconds;
  131. if ( resizeRendererToDisplaySize( renderer ) ) {
  132. const canvas = renderer.domElement;
  133. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  134. camera.updateProjectionMatrix();
  135. }
  136. cameraPole.rotation.y = time * .1;
  137. pickHelper.pick( pickPosition, scene, camera, time );
  138. renderer.render( scene, camera );
  139. requestAnimationFrame( render );
  140. }
  141. requestAnimationFrame( render );
  142. function getCanvasRelativePosition( event ) {
  143. const rect = canvas.getBoundingClientRect();
  144. return {
  145. x: ( event.clientX - rect.left ) * canvas.width / rect.width,
  146. y: ( event.clientY - rect.top ) * canvas.height / rect.height,
  147. };
  148. }
  149. function setPickPosition( event ) {
  150. const pos = getCanvasRelativePosition( event );
  151. pickPosition.x = ( pos.x / canvas.width ) * 2 - 1;
  152. pickPosition.y = ( pos.y / canvas.height ) * - 2 + 1; // note we flip Y
  153. }
  154. function clearPickPosition() {
  155. // unlike the mouse which always has a position
  156. // if the user stops touching the screen we want
  157. // to stop picking. For now we just pick a value
  158. // unlikely to pick something
  159. pickPosition.x = - 100000;
  160. pickPosition.y = - 100000;
  161. }
  162. window.addEventListener( 'mousemove', setPickPosition );
  163. window.addEventListener( 'mouseout', clearPickPosition );
  164. window.addEventListener( 'mouseleave', clearPickPosition );
  165. window.addEventListener( 'touchstart', ( event ) => {
  166. // prevent the window from scrolling
  167. event.preventDefault();
  168. setPickPosition( event.touches[ 0 ] );
  169. }, { passive: false } );
  170. window.addEventListener( 'touchmove', ( event ) => {
  171. setPickPosition( event.touches[ 0 ] );
  172. } );
  173. window.addEventListener( 'touchend', clearPickPosition );
  174. }
  175. main();
  176. </script>
  177. </html>