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

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