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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 src="../3rdparty/dat.gui.min.js"></script>
  64. <script>
  65. 'use strict';
  66. /* global THREE, dat */
  67. function main() {
  68. const canvas = document.querySelector('#c');
  69. const renderer = new THREE.WebGLRenderer({canvas: canvas});
  70. const fov = 60;
  71. const aspect = 2; // the canvas default
  72. const near = 0.1;
  73. const far = 10;
  74. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  75. camera.position.z = 2.5;
  76. const controls = new THREE.OrbitControls(camera, canvas);
  77. controls.enableDamping = true;
  78. controls.dampingFactor = 0.05;
  79. controls.rotateSpeed = 0.1;
  80. controls.enablePan = false;
  81. controls.minDistance = 1.2;
  82. controls.maxDistance = 4;
  83. controls.update();
  84. const scene = new THREE.Scene();
  85. scene.background = new THREE.Color('#246');
  86. {
  87. const loader = new THREE.TextureLoader();
  88. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  89. const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
  90. const material = new THREE.MeshBasicMaterial({map: texture});
  91. scene.add(new THREE.Mesh(geometry, material));
  92. }
  93. async function loadJSON(url) {
  94. const req = await fetch(url);
  95. return req.json();
  96. }
  97. let countryInfos;
  98. async function loadCountryData() {
  99. countryInfos = await loadJSON('resources/data/world/country-info.json'); /* threejsfundamentals: url */
  100. const lonFudge = Math.PI * 1.5;
  101. const latFudge = Math.PI;
  102. // these helpers will make it easy to position the boxes
  103. // We can rotate the lon helper on its Y axis to the longitude
  104. const lonHelper = new THREE.Object3D();
  105. // We rotate the latHelper on its X axis to the latitude
  106. const latHelper = new THREE.Object3D();
  107. lonHelper.add(latHelper);
  108. // The position helper moves the object to the edge of the sphere
  109. const positionHelper = new THREE.Object3D();
  110. positionHelper.position.z = 1;
  111. latHelper.add(positionHelper);
  112. const labelParentElem = document.querySelector('#labels');
  113. for (const countryInfo of countryInfos) {
  114. const {lat, lon, min, max, name} = countryInfo;
  115. // adjust the helpers to point to the latitude and longitude
  116. lonHelper.rotation.y = THREE.Math.degToRad(lon) + lonFudge;
  117. latHelper.rotation.x = THREE.Math.degToRad(lat) + latFudge;
  118. // get the position of the lat/lon
  119. positionHelper.updateWorldMatrix(true, false);
  120. const position = new THREE.Vector3();
  121. positionHelper.getWorldPosition(position);
  122. countryInfo.position = position;
  123. // compute the area for each country
  124. const width = max[0] - min[0];
  125. const height = max[1] - min[1];
  126. const area = width * height;
  127. countryInfo.area = area;
  128. // add an element for each country
  129. const elem = document.createElement('div');
  130. elem.textContent = name;
  131. labelParentElem.appendChild(elem);
  132. countryInfo.elem = elem;
  133. }
  134. requestRenderIfNotRequested();
  135. }
  136. loadCountryData();
  137. const tempV = new THREE.Vector3();
  138. const cameraToPoint = new THREE.Vector3();
  139. const cameraPosition = new THREE.Vector3();
  140. const normalMatrix = new THREE.Matrix3();
  141. const settings = {
  142. minArea: 20,
  143. maxVisibleDot: -0.2,
  144. };
  145. const gui = new dat.GUI({width: 300});
  146. gui.add(settings, 'minArea', 0, 50).onChange(requestRenderIfNotRequested);
  147. gui.add(settings, 'maxVisibleDot', -1, 1, 0.01).onChange(requestRenderIfNotRequested);
  148. function updateLabels() {
  149. if (!countryInfos) {
  150. return;
  151. }
  152. const large = settings.minArea * settings.minArea;
  153. // get a matrix that represents a relative orientation of the camera
  154. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  155. // get the camera's position
  156. camera.getWorldPosition(cameraPosition);
  157. for (const countryInfo of countryInfos) {
  158. const {position, elem, area} = countryInfo;
  159. // large enough?
  160. if (area < large) {
  161. elem.style.display = 'none';
  162. continue;
  163. }
  164. // Orient the position based on the camera's orientation.
  165. // Since the sphere is at the origin and the sphere is a unit sphere
  166. // this gives us a camera relative direction vector for the position.
  167. tempV.copy(position);
  168. tempV.applyMatrix3(normalMatrix);
  169. // compute the direction to this position from the camera
  170. cameraToPoint.copy(position);
  171. cameraToPoint.applyMatrix4(camera.matrixWorldInverse).normalize();
  172. // get the dot product of camera relative direction to this position
  173. // on the globe with the direction from the camera to that point.
  174. // -1 = facing directly towards the camera
  175. // 0 = exactly on tangent of the sphere from the camera
  176. // > 0 = facing away
  177. const dot = tempV.dot(cameraToPoint);
  178. // if the orientation is not facing us hide it.
  179. if (dot > settings.maxVisibleDot) {
  180. elem.style.display = 'none';
  181. continue;
  182. }
  183. // restore the element to its default display style
  184. elem.style.display = '';
  185. // get the normalized screen coordinate of that position
  186. // x and y will be in the -1 to +1 range with x = -1 being
  187. // on the left and y = -1 being on the bottom
  188. tempV.copy(position);
  189. tempV.project(camera);
  190. // convert the normalized position to CSS coordinates
  191. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  192. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  193. // move the elem to that position
  194. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  195. // set the zIndex for sorting
  196. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  197. }
  198. }
  199. function resizeRendererToDisplaySize(renderer) {
  200. const canvas = renderer.domElement;
  201. const width = canvas.clientWidth;
  202. const height = canvas.clientHeight;
  203. const needResize = canvas.width !== width || canvas.height !== height;
  204. if (needResize) {
  205. renderer.setSize(width, height, false);
  206. }
  207. return needResize;
  208. }
  209. let renderRequested = false;
  210. function render() {
  211. renderRequested = undefined;
  212. if (resizeRendererToDisplaySize(renderer)) {
  213. const canvas = renderer.domElement;
  214. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  215. camera.updateProjectionMatrix();
  216. }
  217. controls.update();
  218. updateLabels();
  219. renderer.render(scene, camera);
  220. }
  221. render();
  222. function requestRenderIfNotRequested() {
  223. if (!renderRequested) {
  224. renderRequested = true;
  225. requestAnimationFrame(render);
  226. }
  227. }
  228. controls.addEventListener('change', requestRenderIfNotRequested);
  229. window.addEventListener('resize', requestRenderIfNotRequested);
  230. }
  231. main();
  232. </script>
  233. </html>