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

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