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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. html, body {
  10. margin: 0;
  11. font-family: sans-serif;
  12. height: 100%;
  13. }
  14. #c {
  15. width: 100%; /* let our container decide our size */
  16. height: 100%;
  17. display: block;
  18. }
  19. #container {
  20. position: relative; /* makes this the origin of its children */
  21. width: 100%;
  22. height: 100%;
  23. overflow: hidden;
  24. }
  25. #labels {
  26. position: absolute; /* let us position ourself inside the container */
  27. z-index: 0; /* make a new stacking context so children don't sort with rest of page */
  28. left: 0; /* make our position the top left of the container */
  29. top: 0;
  30. color: white;
  31. }
  32. #labels>div {
  33. position: absolute; /* let us position them inside the container */
  34. left: 0; /* make their default position the top left of the container */
  35. top: 0;
  36. cursor: pointer; /* change the cursor to a hand when over us */
  37. font-size: small;
  38. user-select: none; /* don't let the text get selected */
  39. pointer-events: none; /* make us invisible to the pointer */
  40. text-shadow: /* create a black outline */
  41. -1px -1px 0 #000,
  42. 0 -1px 0 #000,
  43. 1px -1px 0 #000,
  44. 1px 0 0 #000,
  45. 1px 1px 0 #000,
  46. 0 1px 0 #000,
  47. -1px 1px 0 #000,
  48. -1px 0 0 #000;
  49. }
  50. #labels>div:hover {
  51. color: red;
  52. }
  53. </style>
  54. </head>
  55. <body>
  56. <div id="container">
  57. <canvas id="c"></canvas>
  58. <div id="labels"></div>
  59. </div>
  60. </body>
  61. <script type="importmap">
  62. {
  63. "imports": {
  64. "three": "../../build/three.module.js",
  65. "three/addons/": "../../examples/jsm/"
  66. }
  67. }
  68. </script>
  69. <script type="module">
  70. import * as THREE from 'three';
  71. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  72. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  73. function main() {
  74. const canvas = document.querySelector( '#c' );
  75. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  76. const fov = 60;
  77. const aspect = 2; // the canvas default
  78. const near = 0.1;
  79. const far = 10;
  80. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  81. camera.position.z = 2.5;
  82. const controls = new OrbitControls( camera, canvas );
  83. controls.enableDamping = true;
  84. controls.enablePan = false;
  85. controls.minDistance = 1.2;
  86. controls.maxDistance = 4;
  87. controls.update();
  88. const scene = new THREE.Scene();
  89. scene.background = new THREE.Color( '#246' );
  90. {
  91. const loader = new THREE.TextureLoader();
  92. const texture = loader.load( 'resources/data/world/country-outlines-4k.png', render );
  93. const geometry = new THREE.SphereGeometry( 1, 64, 32 );
  94. const material = new THREE.MeshBasicMaterial( { map: texture } );
  95. scene.add( new THREE.Mesh( geometry, material ) );
  96. }
  97. async function loadJSON( url ) {
  98. const req = await fetch( url );
  99. return req.json();
  100. }
  101. let countryInfos;
  102. async function loadCountryData() {
  103. countryInfos = await loadJSON( 'resources/data/world/country-info.json' ); /* threejs.org: url */
  104. const lonFudge = Math.PI * 1.5;
  105. const latFudge = Math.PI;
  106. // these helpers will make it easy to position the boxes
  107. // We can rotate the lon helper on its Y axis to the longitude
  108. const lonHelper = new THREE.Object3D();
  109. // We rotate the latHelper on its X axis to the latitude
  110. const latHelper = new THREE.Object3D();
  111. lonHelper.add( latHelper );
  112. // The position helper moves the object to the edge of the sphere
  113. const positionHelper = new THREE.Object3D();
  114. positionHelper.position.z = 1;
  115. latHelper.add( positionHelper );
  116. const labelParentElem = document.querySelector( '#labels' );
  117. for ( const countryInfo of countryInfos ) {
  118. const { lat, lon, min, max, name } = countryInfo;
  119. // adjust the helpers to point to the latitude and longitude
  120. lonHelper.rotation.y = THREE.MathUtils.degToRad( lon ) + lonFudge;
  121. latHelper.rotation.x = THREE.MathUtils.degToRad( lat ) + latFudge;
  122. // get the position of the lat/lon
  123. positionHelper.updateWorldMatrix( true, false );
  124. const position = new THREE.Vector3();
  125. positionHelper.getWorldPosition( position );
  126. countryInfo.position = position;
  127. // compute the area for each country
  128. const width = max[ 0 ] - min[ 0 ];
  129. const height = max[ 1 ] - min[ 1 ];
  130. const area = width * height;
  131. countryInfo.area = area;
  132. // add an element for each country
  133. const elem = document.createElement( 'div' );
  134. elem.textContent = name;
  135. labelParentElem.appendChild( elem );
  136. countryInfo.elem = elem;
  137. }
  138. requestRenderIfNotRequested();
  139. }
  140. loadCountryData();
  141. const tempV = new THREE.Vector3();
  142. const cameraToPoint = new THREE.Vector3();
  143. const cameraPosition = new THREE.Vector3();
  144. const normalMatrix = new THREE.Matrix3();
  145. const settings = {
  146. minArea: 20,
  147. maxVisibleDot: - 0.2,
  148. };
  149. const gui = new GUI( { width: 300 } );
  150. gui.add( settings, 'minArea', 0, 50 ).onChange( requestRenderIfNotRequested );
  151. gui.add( settings, 'maxVisibleDot', - 1, 1, 0.01 ).onChange( requestRenderIfNotRequested );
  152. function updateLabels() {
  153. if ( ! countryInfos ) {
  154. return;
  155. }
  156. const large = settings.minArea * settings.minArea;
  157. // get a matrix that represents a relative orientation of the camera
  158. normalMatrix.getNormalMatrix( camera.matrixWorldInverse );
  159. // get the camera's position
  160. camera.getWorldPosition( cameraPosition );
  161. for ( const countryInfo of countryInfos ) {
  162. const { position, elem, area } = countryInfo;
  163. // large enough?
  164. if ( area < large ) {
  165. elem.style.display = 'none';
  166. continue;
  167. }
  168. // Orient the position based on the camera's orientation.
  169. // Since the sphere is at the origin and the sphere is a unit sphere
  170. // this gives us a camera relative direction vector for the position.
  171. tempV.copy( position );
  172. tempV.applyMatrix3( normalMatrix );
  173. // compute the direction to this position from the camera
  174. cameraToPoint.copy( position );
  175. cameraToPoint.applyMatrix4( camera.matrixWorldInverse ).normalize();
  176. // get the dot product of camera relative direction to this position
  177. // on the globe with the direction from the camera to that point.
  178. // -1 = facing directly towards the camera
  179. // 0 = exactly on tangent of the sphere from the camera
  180. // > 0 = facing away
  181. const dot = tempV.dot( cameraToPoint );
  182. // if the orientation is not facing us hide it.
  183. if ( dot > settings.maxVisibleDot ) {
  184. elem.style.display = 'none';
  185. continue;
  186. }
  187. // restore the element to its default display style
  188. elem.style.display = '';
  189. // get the normalized screen coordinate of that position
  190. // x and y will be in the -1 to +1 range with x = -1 being
  191. // on the left and y = -1 being on the bottom
  192. tempV.copy( position );
  193. tempV.project( camera );
  194. // convert the normalized position to CSS coordinates
  195. const x = ( tempV.x * .5 + .5 ) * canvas.clientWidth;
  196. const y = ( tempV.y * - .5 + .5 ) * canvas.clientHeight;
  197. // move the elem to that position
  198. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  199. // set the zIndex for sorting
  200. elem.style.zIndex = ( - tempV.z * .5 + .5 ) * 100000 | 0;
  201. }
  202. }
  203. function resizeRendererToDisplaySize( renderer ) {
  204. const canvas = renderer.domElement;
  205. const width = canvas.clientWidth;
  206. const height = canvas.clientHeight;
  207. const needResize = canvas.width !== width || canvas.height !== height;
  208. if ( needResize ) {
  209. renderer.setSize( width, height, false );
  210. }
  211. return needResize;
  212. }
  213. let renderRequested = false;
  214. function render() {
  215. renderRequested = undefined;
  216. if ( resizeRendererToDisplaySize( renderer ) ) {
  217. const canvas = renderer.domElement;
  218. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  219. camera.updateProjectionMatrix();
  220. }
  221. controls.update();
  222. updateLabels();
  223. renderer.render( scene, camera );
  224. }
  225. render();
  226. function requestRenderIfNotRequested() {
  227. if ( ! renderRequested ) {
  228. renderRequested = true;
  229. requestAnimationFrame( render );
  230. }
  231. }
  232. controls.addEventListener( 'change', requestRenderIfNotRequested );
  233. window.addEventListener( 'resize', requestRenderIfNotRequested );
  234. }
  235. main();
  236. </script>
  237. </html>