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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. left: 0; /* make our position the top left of the container */
  27. top: 0;
  28. color: white;
  29. }
  30. #labels>div {
  31. position: absolute; /* let us position them inside the container */
  32. left: 0; /* make their default position the top left of the container */
  33. top: 0;
  34. cursor: pointer; /* change the cursor to a hand when over us */
  35. font-size: small;
  36. user-select: none; /* don't let the text get selected */
  37. pointer-events: none; /* make us invisible to the pointer */
  38. text-shadow: /* create a black outline */
  39. -1px -1px 0 #000,
  40. 0 -1px 0 #000,
  41. 1px -1px 0 #000,
  42. 1px 0 0 #000,
  43. 1px 1px 0 #000,
  44. 0 1px 0 #000,
  45. -1px 1px 0 #000,
  46. -1px 0 0 #000;
  47. }
  48. #labels>div:hover {
  49. color: red;
  50. }
  51. </style>
  52. </head>
  53. <body>
  54. <div id="container">
  55. <canvas id="c"></canvas>
  56. <div id="labels"></div>
  57. </div>
  58. </body>
  59. <script src="resources/threejs/r102/three.js"></script>
  60. <script src="resources/threejs/r102/js/utils/BufferGeometryUtils.js"></script>
  61. <script src="resources/threejs/r102/js/controls/OrbitControls.js"></script>
  62. <script src="../3rdparty/dat.gui.min.js"></script>
  63. <script>
  64. 'use strict';
  65. /* global THREE, dat */
  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('#246');
  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, min, max, 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. // compute the area for each country
  123. const width = max[0] - min[0];
  124. const height = max[1] - min[1];
  125. const area = width * height;
  126. countryInfo.area = area;
  127. // add an element for each country
  128. const elem = document.createElement('div');
  129. elem.textContent = name;
  130. labelParentElem.appendChild(elem);
  131. countryInfo.elem = elem;
  132. }
  133. requestRenderIfNotRequested();
  134. }
  135. loadCountryData();
  136. const tempV = new THREE.Vector3();
  137. const cameraToPoint = new THREE.Vector3();
  138. const cameraPosition = new THREE.Vector3();
  139. const normalMatrix = new THREE.Matrix3();
  140. const settings = {
  141. minArea: 20,
  142. maxVisibleDot: -0.2,
  143. };
  144. const gui = new dat.GUI({width: 300});
  145. gui.add(settings, 'minArea', 0, 50).onChange(requestRenderIfNotRequested);
  146. gui.add(settings, 'maxVisibleDot', -1, 1, 0.01).onChange(requestRenderIfNotRequested);
  147. function updateLabels() {
  148. if (!countryInfos) {
  149. return;
  150. }
  151. const large = settings.minArea * settings.minArea;
  152. // get a matrix that represents a relative orientation of the camera
  153. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  154. // get the camera's position
  155. camera.getWorldPosition(cameraPosition);
  156. for (const countryInfo of countryInfos) {
  157. const {position, elem, area} = countryInfo;
  158. // large enough?
  159. if (area < large) {
  160. elem.style.display = 'none';
  161. continue;
  162. }
  163. // Orient the position based on the camera's orientation.
  164. // Since the sphere is at the origin and the sphere is a unit sphere
  165. // this gives us a camera relative direction vector for the position.
  166. tempV.copy(position);
  167. tempV.applyMatrix3(normalMatrix);
  168. // compute the direction to this position from the camera
  169. cameraToPoint.copy(position);
  170. cameraToPoint.applyMatrix4(camera.matrixWorldInverse).normalize();
  171. // get the dot product of camera relative direction to this position
  172. // on the globe with the direction from the camera to that point.
  173. // -1 = facing directly towards the camera
  174. // 0 = exactly on tangent of the sphere from the camera
  175. // > 0 = facing away
  176. const dot = tempV.dot(cameraToPoint);
  177. // if the orientation is not facing us hide it.
  178. if (dot > settings.maxVisibleDot) {
  179. elem.style.display = 'none';
  180. continue;
  181. }
  182. // restore the element to its default display style
  183. elem.style.display = '';
  184. // get the normalized screen coordinate of that position
  185. // x and y will be in the -1 to +1 range with x = -1 being
  186. // on the left and y = -1 being on the bottom
  187. tempV.copy(position);
  188. tempV.project(camera);
  189. // convert the normalized position to CSS coordinates
  190. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  191. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  192. // move the elem to that position
  193. countryInfo.elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  194. }
  195. }
  196. function resizeRendererToDisplaySize(renderer) {
  197. const canvas = renderer.domElement;
  198. const width = canvas.clientWidth;
  199. const height = canvas.clientHeight;
  200. const needResize = canvas.width !== width || canvas.height !== height;
  201. if (needResize) {
  202. renderer.setSize(width, height, false);
  203. }
  204. return needResize;
  205. }
  206. let renderRequested = false;
  207. function render() {
  208. renderRequested = undefined;
  209. if (resizeRendererToDisplaySize(renderer)) {
  210. const canvas = renderer.domElement;
  211. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  212. camera.updateProjectionMatrix();
  213. }
  214. controls.update();
  215. updateLabels();
  216. renderer.render(scene, camera);
  217. }
  218. render();
  219. function requestRenderIfNotRequested() {
  220. if (!renderRequested) {
  221. renderRequested = true;
  222. requestAnimationFrame(render);
  223. }
  224. }
  225. controls.addEventListener('change', requestRenderIfNotRequested);
  226. window.addEventListener('resize', requestRenderIfNotRequested);
  227. }
  228. main();
  229. </script>
  230. </html>