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

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