picking-raycaster-transparency.html 5.9 KB

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