align-html-elements-to-3d.html 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. <!DOCTYPE html><html lang="ja"><head>
  2. <meta charset="utf-8">
  3. <title>でHTML要素を3Dに揃える</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – でHTML要素を3Dに揃える">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="../resources/lesson.css">
  12. <link rel="stylesheet" href="../resources/lang.css">
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../../build/three.module.js"
  17. }
  18. }
  19. </script>
  20. </head>
  21. <body>
  22. <div class="container">
  23. <div class="lesson-title">
  24. <h1>でHTML要素を3Dに揃える</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>この記事はThree.jsの連載記事の1つです。
  29. 最初の記事は<a href="fundamentals.html">Three.jsの基礎知識</a>です。
  30. まだ読んでいない場合、そこから始めると良いかもしれません。</p>
  31. <p>3Dシーンにテキスト表示させたい場合があると思います。
  32. メリットとデメリットを持つ多くの方法があります。</p>
  33. <ul>
  34. <li><p>3Dテキストを使用する</p>
  35. <p><a href="primitives.html">プリミティブの記事</a>を見ると <a href="/docs/#api/ja/geometries/TextGeometry"><code class="notranslate" translate="no">TextGeometry</code></a> があり、3Dテキストが作れます。
  36. ロゴを飛ばすには便利ですが、統計や情報、ラベル付けなどにはあまり便利でないかもしれません。</p>
  37. </li>
  38. <li><p>テキストが描かれたテクスチャを使用する</p>
  39. <p><a href="canvas-textures.html">この記事</a>ではキャンバスをテクスチャとして使いました。
  40. キャンバスにテキストを描画して<a href="billboards.html">ビルボードとして表示できます</a>。
  41. この方法のメリットは、3Dシーンにテキストが組み込まれている事かもしれません。
  42. 3Dシーンの中でPC端末のようなものを描画するには最適かもしれません。</p>
  43. </li>
  44. <li><p>HTML要素を3D空間に合わせて配置する</p>
  45. <p>この方法のメリットは全てのHTMLを使えます。
  46. HTMLは複数の要素を持てます。
  47. また、CSSでスタイルを整えられます。
  48. 実際のテキストなのでユーザーが選択する事もできます。</p>
  49. </li>
  50. </ul>
  51. <p>この記事では、HTML要素を3D空間に合わせて配置を取り上げます。</p>
  52. <p>まずは簡単に始めてみましょう。
  53. いくつかのプリミティブで3Dシーンを作り、それぞれのプリミティブにラベルを付けます。
  54. <a href="responsive.html">レスポンシブの記事</a>の例を使います。</p>
  55. <p><a href="lights.html">ライティングの記事</a>のように <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> を追加します。</p>
  56. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from 'three';
  57. +import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
  58. </pre>
  59. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const controls = new OrbitControls(camera, canvas);
  60. controls.target.set(0, 0, 0);
  61. controls.update();
  62. </pre>
  63. <p>ラベル要素を含むHTML要素を追加します。</p>
  64. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;body&gt;
  65. - &lt;canvas id="c"&gt;&lt;/canvas&gt;
  66. + &lt;div id="container"&gt;
  67. + &lt;canvas id="c"&gt;&lt;/canvas&gt;
  68. + &lt;div id="labels"&gt;&lt;/div&gt;
  69. + &lt;/div&gt;
  70. &lt;/body&gt;
  71. </pre>
  72. <p>キャンバスと <code class="notranslate" translate="no">&lt;div id="labels"&gt;</code> の両方を親コンテナ配下に入れて、CSSで重なるように設定できます。</p>
  73. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">#c {
  74. - width: 100%;
  75. - height: 100%;
  76. + width: 100%; /* let our container decide our size */
  77. + height: 100%;
  78. display: block;
  79. }
  80. +#container {
  81. + position: relative; /* makes this the origin of its children */
  82. + width: 100%;
  83. + height: 100%;
  84. + overflow: hidden;
  85. +}
  86. +#labels {
  87. + position: absolute; /* let us position ourself inside the container */
  88. + left: 0; /* make our position the top left of the container */
  89. + top: 0;
  90. + color: white;
  91. +}
  92. </pre>
  93. <p>ラベル自体にもCSSを追加しましょう。</p>
  94. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">#labels&gt;div {
  95. position: absolute; /* let us position them inside the container */
  96. left: 0; /* make their default position the top left of the container */
  97. top: 0;
  98. cursor: pointer; /* change the cursor to a hand when over us */
  99. font-size: large;
  100. user-select: none; /* don't let the text get selected */
  101. text-shadow: /* create a black outline */
  102. -1px -1px 0 #000,
  103. 0 -1px 0 #000,
  104. 1px -1px 0 #000,
  105. 1px 0 0 #000,
  106. 1px 1px 0 #000,
  107. 0 1px 0 #000,
  108. -1px 1px 0 #000,
  109. -1px 0 0 #000;
  110. }
  111. #labels&gt;div:hover {
  112. color: red;
  113. }
  114. </pre>
  115. <p>HTMLに多くのラベル要素を追加する必要はありません。
  116. 立方体を生成する関数 <code class="notranslate" translate="no">makeInstance</code> があります。
  117. この関数にラベル要素も追加してみましょう。</p>
  118. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const labelContainerElem = document.querySelector('#labels');
  119. -function makeInstance(geometry, color, x) {
  120. +function makeInstance(geometry, color, x, name) {
  121. const material = new THREE.MeshPhongMaterial({color});
  122. const cube = new THREE.Mesh(geometry, material);
  123. scene.add(cube);
  124. cube.position.x = x;
  125. + const elem = document.createElement('div');
  126. + elem.textContent = name;
  127. + labelContainerElem.appendChild(elem);
  128. - return cube;
  129. + return {cube, elem};
  130. }
  131. </pre>
  132. <p>立方体ごとに1つずつコンテナに <code class="notranslate" translate="no">&lt;div&gt;</code> を追加しています。
  133. ラベルのために <code class="notranslate" translate="no">cube</code> と <code class="notranslate" translate="no">elem</code> の両方を持つオブジェクトを返します。</p>
  134. <p>この関数を呼び出すには、ラベル名も指定する必要があります。</p>
  135. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cubes = [
  136. - makeInstance(geometry, 0x44aa88, 0),
  137. - makeInstance(geometry, 0x8844aa, -2),
  138. - makeInstance(geometry, 0xaa8844, 2),
  139. + makeInstance(geometry, 0x44aa88, 0, 'Aqua'),
  140. + makeInstance(geometry, 0x8844aa, -2, 'Purple'),
  141. + makeInstance(geometry, 0xaa8844, 2, 'Gold'),
  142. ];
  143. </pre>
  144. <p>あとはレンダリング時にラベル要素を配置します。</p>
  145. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const tempV = new THREE.Vector3();
  146. ...
  147. -cubes.forEach((cube, ndx) =&gt; {
  148. +cubes.forEach((cubeInfo, ndx) =&gt; {
  149. + const {cube, elem} = cubeInfo;
  150. const speed = 1 + ndx * .1;
  151. const rot = time * speed;
  152. cube.rotation.x = rot;
  153. cube.rotation.y = rot;
  154. + // get the position of the center of the cube
  155. + cube.updateWorldMatrix(true, false);
  156. + cube.getWorldPosition(tempV);
  157. +
  158. + // get the normalized screen coordinate of that position
  159. + // x and y will be in the -1 to +1 range with x = -1 being
  160. + // on the left and y = -1 being on the bottom
  161. + tempV.project(camera);
  162. +
  163. + // convert the normalized position to CSS coordinates
  164. + const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  165. + const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  166. +
  167. + // move the elem to that position
  168. + elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  169. });
  170. </pre>
  171. <p>そして、ラベルを対応するオブジェクトに合わせて位置を指定します。</p>
  172. <p></p><div translate="no" class="threejs_example_container notranslate">
  173. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/align-html-to-3d.html"></iframe></div>
  174. <a class="threejs_center" href="/manual/examples/align-html-to-3d.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  175. </div>
  176. <p></p>
  177. <p>動かしてみると対処したい問題がいくつか出ると思います。</p>
  178. <p>1つの問題は、オブジェクトを回転させると全てのラベルが重なってしまいます。</p>
  179. <div class="threejs_center"><img src="../resources/images/overlapping-labels.png" style="width: 307px;"></div>
  180. <p>もう1つの問題は、オブジェクトが錐台の外に出るようにズームアウトしても、ラベルが消えずに表示されたままです。</p>
  181. <p>オブジェクトが重なる問題の解決策は<a href="picking.html">ピッキング記事のピッキングコード</a>を使います。
  182. 画面上のオブジェクトの位置を入力し、<code class="notranslate" translate="no">RayCaster</code> にどのオブジェクトが交差していたか教えてもらいます。
  183. オブジェクトが最初のものでなければ前面に表示されません。</p>
  184. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const tempV = new THREE.Vector3();
  185. +const raycaster = new THREE.Raycaster();
  186. ...
  187. cubes.forEach((cubeInfo, ndx) =&gt; {
  188. const {cube, elem} = cubeInfo;
  189. const speed = 1 + ndx * .1;
  190. const rot = time * speed;
  191. cube.rotation.x = rot;
  192. cube.rotation.y = rot;
  193. // get the position of the center of the cube
  194. cube.updateWorldMatrix(true, false);
  195. cube.getWorldPosition(tempV);
  196. // get the normalized screen coordinate of that position
  197. // x and y will be in the -1 to +1 range with x = -1 being
  198. // on the left and y = -1 being on the bottom
  199. tempV.project(camera);
  200. + // ask the raycaster for all the objects that intersect
  201. + // from the eye toward this object's position
  202. + raycaster.setFromCamera(tempV, camera);
  203. + const intersectedObjects = raycaster.intersectObjects(scene.children);
  204. + // We're visible if the first intersection is this object.
  205. + const show = intersectedObjects.length &amp;&amp; cube === intersectedObjects[0].object;
  206. +
  207. + if (!show) {
  208. + // hide the label
  209. + elem.style.display = 'none';
  210. + } else {
  211. + // un-hide the label
  212. + elem.style.display = '';
  213. // convert the normalized position to CSS coordinates
  214. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  215. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  216. // move the elem to that position
  217. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  218. + }
  219. });
  220. </pre>
  221. <p>これで重なり問題に対応しました。</p>
  222. <p>以下は <code class="notranslate" translate="no">tempV.z</code> をチェックし、オブジェクトの原点が錐台の外にあるかをチェックします。</p>
  223. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">- if (!show) {
  224. + if (!show || Math.abs(tempV.z) &gt; 1) {
  225. // hide the label
  226. elem.style.display = 'none';
  227. </pre>
  228. <p>正規化された座標には計算した <code class="notranslate" translate="no">z</code> の値が含まれており、カメラの錐台の <code class="notranslate" translate="no">near</code> は-1、<code class="notranslate" translate="no">far</code> は+1の値になります。</p>
  229. <p></p><div translate="no" class="threejs_example_container notranslate">
  230. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/align-html-to-3d-w-hiding.html"></iframe></div>
  231. <a class="threejs_center" href="/manual/examples/align-html-to-3d-w-hiding.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  232. </div>
  233. <p></p>
  234. <p>錐台のチェックではオブジェクトの原点をチェックしているだけなので、上記の解決策では失敗します。特に大きなオブジェクトの場合などです。
  235. オブジェクトの原点は錐台の外にあるかもしれませんが、オブジェクトの半分は錐台の中にあるかもしれません。</p>
  236. <p>正しい解決策は、オブジェクト自体が錐台に入っているか確認する事でしょう。
  237. ただし、残念ながらチェックの動作が遅いです。
  238. 3つの立方体の場合は問題ないですが、オブジェクトがたくさんある場合は問題になるかもしれません。</p>
  239. <p>Three.jsには、球体オブジェクトが錐台内にあるかチェックする関数がいくつか用意されています。</p>
  240. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// at init time
  241. const frustum = new THREE.Frustum();
  242. const viewProjection = new THREE.Matrix4();
  243. ...
  244. // before checking
  245. camera.updateMatrix();
  246. camera.updateMatrixWorld();
  247. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  248. ...
  249. // then for each mesh
  250. someMesh.updateMatrix();
  251. someMesh.updateMatrixWorld();
  252. viewProjection.multiplyMatrices(
  253. camera.projectionMatrix, camera.matrixWorldInverse);
  254. frustum.setFromProjectionMatrix(viewProjection);
  255. const inFrustum = frustum.contains(someMesh));
  256. </pre>
  257. <p>現在の重なりの解決策にも同様の問題があります。
  258. ピッキングが遅いです。
  259. <a href="picking.html">ピッキングの記事</a>で取り上げたように、GPUベースのピッキングを使う事もできますがコストがかからない訳ではありません。
  260. どの解決策を選択するかはニーズによります。</p>
  261. <p>もう1つの問題はラベルの表示順序です。
  262. コードを変更してラベルを長くなると</p>
  263. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cubes = [
  264. - makeInstance(geometry, 0x44aa88, 0, 'Aqua'),
  265. - makeInstance(geometry, 0x8844aa, -2, 'Purple'),
  266. - makeInstance(geometry, 0xaa8844, 2, 'Gold'),
  267. + makeInstance(geometry, 0x44aa88, 0, 'Aqua Colored Box'),
  268. + makeInstance(geometry, 0x8844aa, -2, 'Purple Colored Box'),
  269. + makeInstance(geometry, 0xaa8844, 2, 'Gold Colored Box'),
  270. ];
  271. </pre>
  272. <p>折り返さないようにCSSで設定します。</p>
  273. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">#labels&gt;div {
  274. + white-space: nowrap;
  275. </pre>
  276. <p>そうすると次のような問題が発生します。</p>
  277. <div class="threejs_center"><img src="../resources/images/label-sorting-issue.png" style="width: 401px;"></div>
  278. <p>上記では紫のボックスは奥にありますが、紫のボックスのラベルはアクアのボックスの前にあります。</p>
  279. <p>これは各要素の <code class="notranslate" translate="no">zIndex</code> を設定して修正できます。
  280. 投影された位置の <code class="notranslate" translate="no">z</code> は-1(手前)〜+1(奥)の値を持ちます。
  281. <code class="notranslate" translate="no">zIndex</code> は整数である必要があります。
  282. 逆方向の意味で <code class="notranslate" translate="no">zIndex</code> の値が大きい方が手前にある事を意味します。
  283. 以下のコードで動作するはずです。</p>
  284. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// convert the normalized position to CSS coordinates
  285. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  286. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  287. // move the elem to that position
  288. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  289. +// set the zIndex for sorting
  290. +elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  291. </pre>
  292. <p>zIndexを正しく動作させるには、値を分散させるために大きな数値を選ぶ必要があります。
  293. そうしないと多くの値が同じ値になってしまいます。
  294. ラベルがページの他の部分と重ならないように、ラベルのコンテナの <code class="notranslate" translate="no">z-index</code> を設定し、新しい<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context">スタッキングコンテキスト</a>を作成します。</p>
  295. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">#labels {
  296. position: absolute; /* let us position ourself inside the container */
  297. + z-index: 0; /* make a new stacking context so children don't sort with rest of page */
  298. left: 0; /* make our position the top left of the container */
  299. top: 0;
  300. color: white;
  301. z-index: 0;
  302. }
  303. </pre>
  304. <p>これでラベルは常に正しい順序で表示されます。</p>
  305. <p></p><div translate="no" class="threejs_example_container notranslate">
  306. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/align-html-to-3d-w-sorting.html"></iframe></div>
  307. <a class="threejs_center" href="/manual/examples/align-html-to-3d-w-sorting.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  308. </div>
  309. <p></p>
  310. <p>もう1つの問題を確認ために、もう1つの例をやってみましょう。
  311. Googleマップのような地球儀を描いて、国名のラベルを貼ってみましょう。</p>
  312. <p>国境を含む<a href="http://thematicmapping.org/downloads/world_borders.php">このデータ</a>を見つけました。
  313. このデータは<a href="http://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>ライセンスです。</p>
  314. <p>データを読み込んで、国の概要と国名、その位置を含むJSONデータを生成するための<a href="https://github.com/mrdoob/three.js/blob/master/manual/resources/tools/geo-picking/">コード</a>を書いてみました。</p>
  315. <div class="threejs_center"><img src="../examples/resources/data/world/country-outlines-4k.png" style="background: black; width: 700px"></div>
  316. <p>JSONデータは以下のような配列です。</p>
  317. <pre class="prettyprint showlinemods notranslate lang-json" translate="no">[
  318. {
  319. "name": "Algeria",
  320. "min": [
  321. -8.667223,
  322. 18.976387
  323. ],
  324. "max": [
  325. 11.986475,
  326. 37.091385
  327. ],
  328. "area": 238174,
  329. "lat": 28.163,
  330. "lon": 2.632,
  331. "population": {
  332. "2005": 32854159
  333. }
  334. },
  335. ...
  336. </pre>
  337. <p>min、max、lat、lon、これは全て緯度と経度です。</p>
  338. <p>ロードしてみましょう。
  339. このコードは<a href="optimize-lots-of-objects.html">多くのオブジェクトを最適化</a>のコードの流用ですが、オブジェクトをたくさん描画しているわけではないので<a href="rendering-on-demand.html">要求されたレンダリング</a>と同じ解決策を使います。</p>
  340. <p>まずは球体を作り、アウトラインテクスチャを使います。</p>
  341. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  342. const loader = new THREE.TextureLoader();
  343. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  344. const geometry = new THREE.SphereGeometry(1, 64, 32);
  345. const material = new THREE.MeshBasicMaterial({map: texture});
  346. scene.add(new THREE.Mesh(geometry, material));
  347. }
  348. </pre>
  349. <p>ローダー関数を作ってJSONファイルをロードしてみましょう。</p>
  350. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">async function loadJSON(url) {
  351. const req = await fetch(url);
  352. return req.json();
  353. }
  354. </pre>
  355. <p>そして、その関数を呼び出します。</p>
  356. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">let countryInfos;
  357. async function loadCountryData() {
  358. countryInfos = await loadJSON('resources/data/world/country-info.json');
  359. ...
  360. }
  361. requestRenderIfNotRequested();
  362. }
  363. loadCountryData();
  364. </pre>
  365. <p>では、そのデータを使ってラベルを生成して配置してみましょう。</p>
  366. <p><a href="optimize-lots-of-objects.html">多くのオブジェクトを最適化</a>の記事ではヘルパーオブジェクトの小さなシーングラフを設定し、地球儀上の緯度と経度の位置を簡単に計算できるようにしました。
  367. 仕組みの説明はその記事を参照して下さい。</p>
  368. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const lonFudge = Math.PI * 1.5;
  369. const latFudge = Math.PI;
  370. // these helpers will make it easy to position the boxes
  371. // We can rotate the lon helper on its Y axis to the longitude
  372. const lonHelper = new THREE.Object3D();
  373. // We rotate the latHelper on its X axis to the latitude
  374. const latHelper = new THREE.Object3D();
  375. lonHelper.add(latHelper);
  376. // The position helper moves the object to the edge of the sphere
  377. const positionHelper = new THREE.Object3D();
  378. positionHelper.position.z = 1;
  379. latHelper.add(positionHelper);
  380. </pre>
  381. <p>これを使い、各ラベルの位置を計算します。</p>
  382. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const labelParentElem = document.querySelector('#labels');
  383. for (const countryInfo of countryInfos) {
  384. const {lat, lon, name} = countryInfo;
  385. // adjust the helpers to point to the latitude and longitude
  386. lonHelper.rotation.y = THREE.MathUtils.degToRad(lon) + lonFudge;
  387. latHelper.rotation.x = THREE.MathUtils.degToRad(lat) + latFudge;
  388. // get the position of the lat/lon
  389. positionHelper.updateWorldMatrix(true, false);
  390. const position = new THREE.Vector3();
  391. positionHelper.getWorldPosition(position);
  392. countryInfo.position = position;
  393. // add an element for each country
  394. const elem = document.createElement('div');
  395. elem.textContent = name;
  396. labelParentElem.appendChild(elem);
  397. countryInfo.elem = elem;
  398. </pre>
  399. <p>上記のコードは、立方体のラベルを作成するために書いたコードに非常に似てます。
  400. これで配列 <code class="notranslate" translate="no">countryInfos</code> ができました。
  401. 国ごとのlabel要素に <code class="notranslate" translate="no">elem</code> プロパティを追加し、位置を表す <code class="notranslate" translate="no">position</code> を追加しました。</p>
  402. <p>立方体の場合と同じく、ラベルの位置とレンダリング時間を更新します。</p>
  403. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const tempV = new THREE.Vector3();
  404. function updateLabels() {
  405. // exit if we have not yet loaded the JSON file
  406. if (!countryInfos) {
  407. return;
  408. }
  409. for (const countryInfo of countryInfos) {
  410. const {position, elem} = countryInfo;
  411. // get the normalized screen coordinate of that position
  412. // x and y will be in the -1 to +1 range with x = -1 being
  413. // on the left and y = -1 being on the bottom
  414. tempV.copy(position);
  415. tempV.project(camera);
  416. // convert the normalized position to CSS coordinates
  417. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  418. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  419. // move the elem to that position
  420. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  421. // set the zIndex for sorting
  422. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  423. }
  424. }
  425. </pre>
  426. <p>上記のコードは、前の立方体のコードと実質的に似ています。
  427. 唯一の大きな違いは、初期化時にラベルの位置を事前に計算しました。
  428. 地球儀が動かないため可能です。カメラだけが動きます。</p>
  429. <p>最後にループ処理するrender関数の中で <code class="notranslate" translate="no">updateLabels</code> を呼び出します。</p>
  430. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render() {
  431. renderRequested = false;
  432. if (resizeRendererToDisplaySize(renderer)) {
  433. const canvas = renderer.domElement;
  434. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  435. camera.updateProjectionMatrix();
  436. }
  437. controls.update();
  438. + updateLabels();
  439. renderer.render(scene, camera);
  440. }
  441. </pre>
  442. <p>そして、これが結果です。</p>
  443. <p></p><div translate="no" class="threejs_example_container notranslate">
  444. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/align-html-elements-to-3d-globe-too-many-labels.html"></iframe></div>
  445. <a class="threejs_center" href="/manual/examples/align-html-elements-to-3d-globe-too-many-labels.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  446. </div>
  447. <p></p>
  448. <p>ラベルが多すぎる!</p>
  449. <p>問題は2つあります。</p>
  450. <ol>
  451. <li><p>地球儀の背面の国のラベルも表示されてる</p>
  452. </li>
  453. <li><p>ラベルが多すぎる</p>
  454. </li>
  455. </ol>
  456. <p>問題1では球体以外に交わるものがないので、上記で説明したように <code class="notranslate" translate="no">RayCaster</code> を使う事はできません。
  457. 代わりにできるのは特定の国が離れているか確認する事です。
  458. これはラベルの位置が球体の周囲にあるために動作します。
  459. 実際には単位球体を使っており、半径1.0の球体です。
  460. つまり、位置は単位方向になっており計算が比較的簡単になります。</p>
  461. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const tempV = new THREE.Vector3();
  462. +const cameraToPoint = new THREE.Vector3();
  463. +const cameraPosition = new THREE.Vector3();
  464. +const normalMatrix = new THREE.Matrix3();
  465. function updateLabels() {
  466. // exit if we have not yet loaded the JSON file
  467. if (!countryInfos) {
  468. return;
  469. }
  470. + const minVisibleDot = 0.2;
  471. + // get a matrix that represents a relative orientation of the camera
  472. + normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  473. + // get the camera's position
  474. + camera.getWorldPosition(cameraPosition);
  475. for (const countryInfo of countryInfos) {
  476. const {position, elem} = countryInfo;
  477. + // Orient the position based on the camera's orientation.
  478. + // Since the sphere is at the origin and the sphere is a unit sphere
  479. + // this gives us a camera relative direction vector for the position.
  480. + tempV.copy(position);
  481. + tempV.applyMatrix3(normalMatrix);
  482. +
  483. + // compute the direction to this position from the camera
  484. + cameraToPoint.copy(position);
  485. + cameraToPoint.applyMatrix4(camera.matrixWorldInverse).normalize();
  486. +
  487. + // get the dot product of camera relative direction to this position
  488. + // on the globe with the direction from the camera to that point.
  489. + // 1 = facing directly towards the camera
  490. + // 0 = exactly on tangent of the sphere from the camera
  491. + // &lt; 0 = facing away
  492. + const dot = tempV.dot(cameraToPoint);
  493. +
  494. + // if the orientation is not facing us hide it.
  495. + if (dot &lt; minVisibleDot) {
  496. + elem.style.display = 'none';
  497. + continue;
  498. + }
  499. +
  500. + // restore the element to its default display style
  501. + elem.style.display = '';
  502. // get the normalized screen coordinate of that position
  503. // x and y will be in the -1 to +1 range with x = -1 being
  504. // on the left and y = -1 being on the bottom
  505. tempV.copy(position);
  506. tempV.project(camera);
  507. // convert the normalized position to CSS coordinates
  508. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  509. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  510. // move the elem to that position
  511. countryInfo.elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  512. // set the zIndex for sorting
  513. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  514. }
  515. }
  516. </pre>
  517. <p>上記では位置を方向として使用し、カメラに対して相対的にその方向を取得しています。
  518. カメラから地球儀上のその位置までのカメラの相対的な方向を取得し、<em>内積</em> を取得します。
  519. 内積はベクトル間の角度のコサインを返します。
  520. これで -1 〜 +1までの値を取得できます。
  521. -1はラベルがカメラに向いており、0はラベルがカメラから見て球体の端にあって、0より大きいものは背面にあります。
  522. その値を使用してラベル要素の表示・非表示をします。</p>
  523. <div class="spread">
  524. <div>
  525. <div data-diagram="dotProduct" style="height: 400px"></div>
  526. </div>
  527. </div>
  528. <p>上記の図では、カメラからその位置までのラベルの向きの内積を表しています。
  529. 方向を回転させるとカメラに直接向いている時は、内積は-1.0になります。
  530. カメラに相対する球体の接線上にある時は0.0になります。
  531. 別の言い方をすれば、2つのベクトルがお互いに90度垂直な時は0になります。</p>
  532. <p>問題2はラベルが多すぎて、どのラベルを表示するか決める方法が必要です。
  533. 1つの方法は大きな国のラベルのみを表示します。
  534. 読込中のデータには、国がカバーする領域の最小値と最大値が含まれています。
  535. そこから面積を計算し、その面積を使い表示するか決められます。</p>
  536. <p>初期化時に面積を計算してみましょう。</p>
  537. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const labelParentElem = document.querySelector('#labels');
  538. for (const countryInfo of countryInfos) {
  539. const {lat, lon, min, max, name} = countryInfo;
  540. // adjust the helpers to point to the latitude and longitude
  541. lonHelper.rotation.y = THREE.MathUtils.degToRad(lon) + lonFudge;
  542. latHelper.rotation.x = THREE.MathUtils.degToRad(lat) + latFudge;
  543. // get the position of the lat/lon
  544. positionHelper.updateWorldMatrix(true, false);
  545. const position = new THREE.Vector3();
  546. positionHelper.getWorldPosition(position);
  547. countryInfo.position = position;
  548. + // compute the area for each country
  549. + const width = max[0] - min[0];
  550. + const height = max[1] - min[1];
  551. + const area = width * height;
  552. + countryInfo.area = area;
  553. // add an element for each country
  554. const elem = document.createElement('div');
  555. elem.textContent = name;
  556. labelParentElem.appendChild(elem);
  557. countryInfo.elem = elem;
  558. }
  559. </pre>
  560. <p>レンダリング時にその領域を使い、ラベルを表示するか決めましょう。</p>
  561. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const large = 20 * 20;
  562. const maxVisibleDot = 0.2;
  563. // get a matrix that represents a relative orientation of the camera
  564. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  565. // get the camera's position
  566. camera.getWorldPosition(cameraPosition);
  567. for (const countryInfo of countryInfos) {
  568. - const {position, elem} = countryInfo;
  569. + const {position, elem, area} = countryInfo;
  570. + // large enough?
  571. + if (area &lt; large) {
  572. + elem.style.display = 'none';
  573. + continue;
  574. + }
  575. ...
  576. </pre>
  577. <p>私にはこの設定のための良い値が何か分からないです。
  578. 値を操作できるようにGUIを追加します。</p>
  579. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from 'three';
  580. import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
  581. +import {GUI} from 'three/addons/libs/lil-gui.module.min.js';
  582. </pre>
  583. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const settings = {
  584. + minArea: 20,
  585. + maxVisibleDot: -0.2,
  586. +};
  587. +const gui = new GUI({width: 300});
  588. +gui.add(settings, 'minArea', 0, 50).onChange(requestRenderIfNotRequested);
  589. +gui.add(settings, 'maxVisibleDot', -1, 1, 0.01).onChange(requestRenderIfNotRequested);
  590. function updateLabels() {
  591. if (!countryInfos) {
  592. return;
  593. }
  594. - const large = 20 * 20;
  595. - const maxVisibleDot = -0.2;
  596. + const large = settings.minArea * settings.minArea;
  597. // get a matrix that represents a relative orientation of the camera
  598. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  599. // get the camera's position
  600. camera.getWorldPosition(cameraPosition);
  601. for (const countryInfo of countryInfos) {
  602. ...
  603. // if the orientation is not facing us hide it.
  604. - if (dot &gt; maxVisibleDot) {
  605. + if (dot &gt; settings.maxVisibleDot) {
  606. elem.style.display = 'none';
  607. continue;
  608. }
  609. </pre>
  610. <p>その結果が以下です。</p>
  611. <p></p><div translate="no" class="threejs_example_container notranslate">
  612. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/align-html-elements-to-3d-globe.html"></iframe></div>
  613. <a class="threejs_center" href="/manual/examples/align-html-elements-to-3d-globe.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  614. </div>
  615. <p></p>
  616. <p>回転させて地球儀の背面にいったラベルが消えるようになりました。
  617. <code class="notranslate" translate="no">minVisibleDot</code> を調整してカットオフの変化を見る事ができます。
  618. また、<code class="notranslate" translate="no">minArea</code> の値を調整して大きな国や小さな国を表示したりもできます。</p>
  619. <p>このコード修正を通して、Googleマップにどれだけの労力が投入されているのかを実感しました。
  620. Googleマップの開発者は、どのラベルを表示するかを決定しなければなりません。
  621. 色んな基準を使っているのは間違いないですね。
  622. 例えば、あなたの現在地、デフォルトの言語設定、アカウントを持っている場合はアカウントの設定、人口や人気度を使用している可能性、ビューの中央にある国を優先している可能性など。
  623. 考える事はたくさんあります。</p>
  624. <p>これらの例がHTML要素を3Dに配置する方法について、あなたにいくつかのアイデアを与えられたと思います。
  625. 変更したい事がいくつかあります。</p>
  626. <p>次は<a href="indexed-textures.html">国を選んでハイライトする</a>ようにしてみましょう。</p>
  627. <p><link rel="stylesheet" href="../resources/threejs-align-html-elements-to-3d.css"></p>
  628. <script type="module" src="../resources/threejs-align-html-elements-to-3d.js"></script>
  629. </div>
  630. </div>
  631. </div>
  632. <script src="../resources/prettify.js"></script>
  633. <script src="../resources/lesson.js"></script>
  634. </body></html>