threejs-picking-raycaster.html 5.4 KB

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