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

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