threejs-picking-raycaster.html 5.1 KB

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