threejs-align-html-elements-to-3d-globe-too-many-labels.html 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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/r114/build/three.module.js';
  62. import {OrbitControls} from './resources/threejs/r114/examples/jsm/controls/OrbitControls.js';
  63. function main() {
  64. const canvas = document.querySelector('#c');
  65. const renderer = new THREE.WebGLRenderer({canvas});
  66. const fov = 60;
  67. const aspect = 2; // the canvas default
  68. const near = 0.1;
  69. const far = 10;
  70. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  71. camera.position.z = 2.5;
  72. const controls = new OrbitControls(camera, canvas);
  73. controls.enableDamping = true;
  74. controls.enablePan = false;
  75. controls.minDistance = 1.2;
  76. controls.maxDistance = 4;
  77. controls.update();
  78. const scene = new THREE.Scene();
  79. scene.background = new THREE.Color('#236');
  80. {
  81. const loader = new THREE.TextureLoader();
  82. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  83. const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
  84. const material = new THREE.MeshBasicMaterial({map: texture});
  85. scene.add(new THREE.Mesh(geometry, material));
  86. }
  87. async function loadJSON(url) {
  88. const req = await fetch(url);
  89. return req.json();
  90. }
  91. let countryInfos;
  92. async function loadCountryData() {
  93. countryInfos = await loadJSON('resources/data/world/country-info.json'); /* threejsfundamentals: url */
  94. const lonFudge = Math.PI * 1.5;
  95. const latFudge = Math.PI;
  96. // these helpers will make it easy to position the boxes
  97. // We can rotate the lon helper on its Y axis to the longitude
  98. const lonHelper = new THREE.Object3D();
  99. // We rotate the latHelper on its X axis to the latitude
  100. const latHelper = new THREE.Object3D();
  101. lonHelper.add(latHelper);
  102. // The position helper moves the object to the edge of the sphere
  103. const positionHelper = new THREE.Object3D();
  104. positionHelper.position.z = 1;
  105. latHelper.add(positionHelper);
  106. const labelParentElem = document.querySelector('#labels');
  107. for (const countryInfo of countryInfos) {
  108. const {lat, lon, name} = countryInfo;
  109. // adjust the helpers to point to the latitude and longitude
  110. lonHelper.rotation.y = THREE.MathUtils.degToRad(lon) + lonFudge;
  111. latHelper.rotation.x = THREE.MathUtils.degToRad(lat) + latFudge;
  112. // get the position of the lat/lon
  113. positionHelper.updateWorldMatrix(true, false);
  114. const position = new THREE.Vector3();
  115. positionHelper.getWorldPosition(position);
  116. countryInfo.position = position;
  117. // add an element for each country
  118. const elem = document.createElement('div');
  119. elem.textContent = name;
  120. labelParentElem.appendChild(elem);
  121. countryInfo.elem = elem;
  122. }
  123. requestRenderIfNotRequested();
  124. }
  125. loadCountryData();
  126. const tempV = new THREE.Vector3();
  127. function updateLabels() {
  128. // exit if we have not yet loaded the JSON file
  129. if (!countryInfos) {
  130. return;
  131. }
  132. for (const countryInfo of countryInfos) {
  133. const {position, elem} = countryInfo;
  134. // get the normalized screen coordinate of that position
  135. // x and y will be in the -1 to +1 range with x = -1 being
  136. // on the left and y = -1 being on the bottom
  137. tempV.copy(position);
  138. tempV.project(camera);
  139. // convert the normalized position to CSS coordinates
  140. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  141. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  142. // move the elem to that position
  143. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  144. // set the zIndex for sorting
  145. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  146. }
  147. }
  148. function resizeRendererToDisplaySize(renderer) {
  149. const canvas = renderer.domElement;
  150. const width = canvas.clientWidth;
  151. const height = canvas.clientHeight;
  152. const needResize = canvas.width !== width || canvas.height !== height;
  153. if (needResize) {
  154. renderer.setSize(width, height, false);
  155. }
  156. return needResize;
  157. }
  158. let renderRequested = false;
  159. function render() {
  160. renderRequested = undefined;
  161. if (resizeRendererToDisplaySize(renderer)) {
  162. const canvas = renderer.domElement;
  163. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  164. camera.updateProjectionMatrix();
  165. }
  166. controls.update();
  167. updateLabels();
  168. renderer.render(scene, camera);
  169. }
  170. render();
  171. function requestRenderIfNotRequested() {
  172. if (!renderRequested) {
  173. renderRequested = true;
  174. requestAnimationFrame(render);
  175. }
  176. }
  177. controls.addEventListener('change', requestRenderIfNotRequested);
  178. window.addEventListener('resize', requestRenderIfNotRequested);
  179. }
  180. main();
  181. </script>
  182. </html>