threejs-picking-raycaster-transparency.html 5.6 KB

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