threejs-align-html-elements-to-3d-globe.html 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 - Align HTML Elements to 3D Globe</title>
  8. <style>
  9. body {
  10. margin: 0;
  11. font-family: sans-serif;
  12. }
  13. #c {
  14. width: 100%; /* let our container decide our size */
  15. height: 100%;
  16. display: block;
  17. }
  18. #container {
  19. position: relative; /* makes this the origin of its children */
  20. width: 100vw;
  21. height: 100vh;
  22. overflow: hidden;
  23. }
  24. #labels {
  25. position: absolute; /* let us position ourself inside the container */
  26. z-index: 0; /* make a new stacking context so children don't sort with rest of page */
  27. left: 0; /* make our position the top left of the container */
  28. top: 0;
  29. color: white;
  30. }
  31. #labels>div {
  32. position: absolute; /* let us position them inside the container */
  33. left: 0; /* make their default position the top left of the container */
  34. top: 0;
  35. cursor: pointer; /* change the cursor to a hand when over us */
  36. font-size: small;
  37. user-select: none; /* don't let the text get selected */
  38. pointer-events: none; /* make us invisible to the pointer */
  39. text-shadow: /* create a black outline */
  40. -1px -1px 0 #000,
  41. 0 -1px 0 #000,
  42. 1px -1px 0 #000,
  43. 1px 0 0 #000,
  44. 1px 1px 0 #000,
  45. 0 1px 0 #000,
  46. -1px 1px 0 #000,
  47. -1px 0 0 #000;
  48. }
  49. #labels>div:hover {
  50. color: red;
  51. }
  52. </style>
  53. </head>
  54. <body>
  55. <div id="container">
  56. <canvas id="c"></canvas>
  57. <div id="labels"></div>
  58. </div>
  59. </body>
  60. <script type="module">
  61. import * as THREE from './resources/threejs/r119/build/three.module.js';
  62. import {OrbitControls} from './resources/threejs/r119/examples/jsm/controls/OrbitControls.js';
  63. import {GUI} from '../3rdparty/dat.gui.module.js';
  64. function main() {
  65. const canvas = document.querySelector('#c');
  66. const renderer = new THREE.WebGLRenderer({canvas});
  67. const fov = 60;
  68. const aspect = 2; // the canvas default
  69. const near = 0.1;
  70. const far = 10;
  71. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  72. camera.position.z = 2.5;
  73. const controls = new OrbitControls(camera, canvas);
  74. controls.enableDamping = true;
  75. controls.enablePan = false;
  76. controls.minDistance = 1.2;
  77. controls.maxDistance = 4;
  78. controls.update();
  79. const scene = new THREE.Scene();
  80. scene.background = new THREE.Color('#246');
  81. {
  82. const loader = new THREE.TextureLoader();
  83. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  84. const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
  85. const material = new THREE.MeshBasicMaterial({map: texture});
  86. scene.add(new THREE.Mesh(geometry, material));
  87. }
  88. async function loadJSON(url) {
  89. const req = await fetch(url);
  90. return req.json();
  91. }
  92. let countryInfos;
  93. async function loadCountryData() {
  94. countryInfos = await loadJSON('resources/data/world/country-info.json'); /* threejsfundamentals: url */
  95. const lonFudge = Math.PI * 1.5;
  96. const latFudge = Math.PI;
  97. // these helpers will make it easy to position the boxes
  98. // We can rotate the lon helper on its Y axis to the longitude
  99. const lonHelper = new THREE.Object3D();
  100. // We rotate the latHelper on its X axis to the latitude
  101. const latHelper = new THREE.Object3D();
  102. lonHelper.add(latHelper);
  103. // The position helper moves the object to the edge of the sphere
  104. const positionHelper = new THREE.Object3D();
  105. positionHelper.position.z = 1;
  106. latHelper.add(positionHelper);
  107. const labelParentElem = document.querySelector('#labels');
  108. for (const countryInfo of countryInfos) {
  109. const {lat, lon, min, max, name} = countryInfo;
  110. // adjust the helpers to point to the latitude and longitude
  111. lonHelper.rotation.y = THREE.MathUtils.degToRad(lon) + lonFudge;
  112. latHelper.rotation.x = THREE.MathUtils.degToRad(lat) + latFudge;
  113. // get the position of the lat/lon
  114. positionHelper.updateWorldMatrix(true, false);
  115. const position = new THREE.Vector3();
  116. positionHelper.getWorldPosition(position);
  117. countryInfo.position = position;
  118. // compute the area for each country
  119. const width = max[0] - min[0];
  120. const height = max[1] - min[1];
  121. const area = width * height;
  122. countryInfo.area = area;
  123. // add an element for each country
  124. const elem = document.createElement('div');
  125. elem.textContent = name;
  126. labelParentElem.appendChild(elem);
  127. countryInfo.elem = elem;
  128. }
  129. requestRenderIfNotRequested();
  130. }
  131. loadCountryData();
  132. const tempV = new THREE.Vector3();
  133. const cameraToPoint = new THREE.Vector3();
  134. const cameraPosition = new THREE.Vector3();
  135. const normalMatrix = new THREE.Matrix3();
  136. const settings = {
  137. minArea: 20,
  138. maxVisibleDot: -0.2,
  139. };
  140. const gui = new GUI({width: 300});
  141. gui.add(settings, 'minArea', 0, 50).onChange(requestRenderIfNotRequested);
  142. gui.add(settings, 'maxVisibleDot', -1, 1, 0.01).onChange(requestRenderIfNotRequested);
  143. function updateLabels() {
  144. if (!countryInfos) {
  145. return;
  146. }
  147. const large = settings.minArea * settings.minArea;
  148. // get a matrix that represents a relative orientation of the camera
  149. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  150. // get the camera's position
  151. camera.getWorldPosition(cameraPosition);
  152. for (const countryInfo of countryInfos) {
  153. const {position, elem, area} = countryInfo;
  154. // large enough?
  155. if (area < large) {
  156. elem.style.display = 'none';
  157. continue;
  158. }
  159. // Orient the position based on the camera's orientation.
  160. // Since the sphere is at the origin and the sphere is a unit sphere
  161. // this gives us a camera relative direction vector for the position.
  162. tempV.copy(position);
  163. tempV.applyMatrix3(normalMatrix);
  164. // compute the direction to this position from the camera
  165. cameraToPoint.copy(position);
  166. cameraToPoint.applyMatrix4(camera.matrixWorldInverse).normalize();
  167. // get the dot product of camera relative direction to this position
  168. // on the globe with the direction from the camera to that point.
  169. // -1 = facing directly towards the camera
  170. // 0 = exactly on tangent of the sphere from the camera
  171. // > 0 = facing away
  172. const dot = tempV.dot(cameraToPoint);
  173. // if the orientation is not facing us hide it.
  174. if (dot > settings.maxVisibleDot) {
  175. elem.style.display = 'none';
  176. continue;
  177. }
  178. // restore the element to its default display style
  179. elem.style.display = '';
  180. // get the normalized screen coordinate of that position
  181. // x and y will be in the -1 to +1 range with x = -1 being
  182. // on the left and y = -1 being on the bottom
  183. tempV.copy(position);
  184. tempV.project(camera);
  185. // convert the normalized position to CSS coordinates
  186. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  187. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  188. // move the elem to that position
  189. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  190. // set the zIndex for sorting
  191. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  192. }
  193. }
  194. function resizeRendererToDisplaySize(renderer) {
  195. const canvas = renderer.domElement;
  196. const width = canvas.clientWidth;
  197. const height = canvas.clientHeight;
  198. const needResize = canvas.width !== width || canvas.height !== height;
  199. if (needResize) {
  200. renderer.setSize(width, height, false);
  201. }
  202. return needResize;
  203. }
  204. let renderRequested = false;
  205. function render() {
  206. renderRequested = undefined;
  207. if (resizeRendererToDisplaySize(renderer)) {
  208. const canvas = renderer.domElement;
  209. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  210. camera.updateProjectionMatrix();
  211. }
  212. controls.update();
  213. updateLabels();
  214. renderer.render(scene, camera);
  215. }
  216. render();
  217. function requestRenderIfNotRequested() {
  218. if (!renderRequested) {
  219. renderRequested = true;
  220. requestAnimationFrame(render);
  221. }
  222. }
  223. controls.addEventListener('change', requestRenderIfNotRequested);
  224. window.addEventListener('resize', requestRenderIfNotRequested);
  225. }
  226. main();
  227. </script>
  228. </html>