picking-raycaster.html 5.4 KB

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