canvas-textures.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <!DOCTYPE html><html lang="ja"><head>
  2. <meta charset="utf-8">
  3. <title>のキャンバステクスチャ</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 – のキャンバステクスチャ">
  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>のキャンバステクスチャ</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>この記事は<a href="textures.html">Three.jsのテクスチャ</a>からの続きです。
  29. まだ読んでない人はそちらから先に読んでみるといいかもしれません。</p>
  30. <p><a href="textures.html">前回のテクスチャの記事</a>ではテクスチャは画像ファイルを使っていました。
  31. 実行時にテクスチャを生成したい場合もあります。
  32. これを行う方法の1つは <a href="/docs/#api/ja/textures/CanvasTexture"><code class="notranslate" translate="no">CanvasTexture</code></a> を使用する事です。</p>
  33. <p>キャンバステクスチャは <code class="notranslate" translate="no">&lt;canvas&gt;</code> を入力として受け取ります。
  34. 2D canvas APIでキャンバスに描画する方法を知らない場合、<a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial">MDNに良いチュートリアルがあります</a>。</p>
  35. <p>簡単なキャンバスのプログラムを作ってみましょう。
  36. ランダムな場所にランダムな色で点を描画します。</p>
  37. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const ctx = document.createElement('canvas').getContext('2d');
  38. document.body.appendChild(ctx.canvas);
  39. ctx.canvas.width = 256;
  40. ctx.canvas.height = 256;
  41. ctx.fillStyle = '#FFF';
  42. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  43. function randInt(min, max) {
  44. if (max === undefined) {
  45. max = min;
  46. min = 0;
  47. }
  48. return Math.random() * (max - min) + min | 0;
  49. }
  50. function drawRandomDot() {
  51. ctx.fillStyle = `#${randInt(0x1000000).toString(16).padStart(6, '0')}`;
  52. ctx.beginPath();
  53. const x = randInt(256);
  54. const y = randInt(256);
  55. const radius = randInt(10, 64);
  56. ctx.arc(x, y, radius, 0, Math.PI * 2);
  57. ctx.fill();
  58. }
  59. function render() {
  60. drawRandomDot();
  61. requestAnimationFrame(render);
  62. }
  63. requestAnimationFrame(render);
  64. </pre>
  65. <p>結構簡単ですね。</p>
  66. <p></p><div translate="no" class="threejs_example_container notranslate">
  67. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-random-dots.html"></iframe></div>
  68. <a class="threejs_center" href="/manual/examples/canvas-random-dots.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  69. </div>
  70. <p></p>
  71. <p>これをテクスチャとして使ってみましょう。
  72. まずは<a href="textures.html">前回の記事</a>の立方体のテクスチャにしてみます。
  73. 画像を読込するコードを削除します。
  74. 代わりにキャンバスを作成し <a href="/docs/#api/ja/textures/CanvasTexture"><code class="notranslate" translate="no">CanvasTexture</code></a> を作成してキャンバスに渡します。</p>
  75. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cubes = []; // just an array we can use to rotate the cubes
  76. -const loader = new THREE.TextureLoader();
  77. -
  78. +const ctx = document.createElement('canvas').getContext('2d');
  79. +ctx.canvas.width = 256;
  80. +ctx.canvas.height = 256;
  81. +ctx.fillStyle = '#FFF';
  82. +ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  83. +const texture = new THREE.CanvasTexture(ctx.canvas);
  84. const material = new THREE.MeshBasicMaterial({
  85. - map: loader.load('resources/images/wall.jpg'),
  86. + map: texture,
  87. });
  88. const cube = new THREE.Mesh(geometry, material);
  89. scene.add(cube);
  90. cubes.push(cube); // add to our list of cubes to rotate
  91. </pre>
  92. <p>描画のループ処理でランダムな点を描画するコードを呼び出します。</p>
  93. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render(time) {
  94. time *= 0.001;
  95. if (resizeRendererToDisplaySize(renderer)) {
  96. const canvas = renderer.domElement;
  97. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  98. camera.updateProjectionMatrix();
  99. }
  100. + drawRandomDot();
  101. + texture.needsUpdate = true;
  102. cubes.forEach((cube, ndx) =&gt; {
  103. const speed = .2 + ndx * .1;
  104. const rot = time * speed;
  105. cube.rotation.x = rot;
  106. cube.rotation.y = rot;
  107. });
  108. renderer.render(scene, camera);
  109. requestAnimationFrame(render);
  110. }
  111. </pre>
  112. <p>唯一の余計な事は <a href="/docs/#api/ja/textures/CanvasTexture"><code class="notranslate" translate="no">CanvasTexture</code></a> の <code class="notranslate" translate="no">needsUpdate</code> プロパティを設定し、Three.jsにキャンバスの最新のコンテンツでテクスチャを更新する事です。</p>
  113. <p>これでキャンバスのテクスチャキューブができました。</p>
  114. <p></p><div translate="no" class="threejs_example_container notranslate">
  115. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-textured-cube.html"></iframe></div>
  116. <a class="threejs_center" href="/manual/examples/canvas-textured-cube.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  117. </div>
  118. <p></p>
  119. <p>注意点としてThree.jsを使ってキャンバスに描画する場合、
  120. <a href="rendertargets.html">この記事</a> で説明している <code class="notranslate" translate="no">RenderTarget</code> を使った方が良いでしょう。</p>
  121. <p>キャンバステクスチャの一般的な使用例は、シーンにテキストを提供する事です。
  122. 例えばキャラクターのバッジに名前を入れたい場合、キャンバステクスチャを使いバッジのテクスチャを作成します。</p>
  123. <p>3人のキャラクターがいるシーンを作り、それぞれにバッジやラベルを付けてみましょう。</p>
  124. <p>上記の例から立方体に関連する全てのコードを削除してみましょう。
  125. 背景を白にして、<a href="lights.html">ライト</a>を2つ追加してみましょう。</p>
  126. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  127. +scene.background = new THREE.Color('white');
  128. +
  129. +function addLight(position) {
  130. + const color = 0xFFFFFF;
  131. + const intensity = 1;
  132. + const light = new THREE.DirectionalLight(color, intensity);
  133. + light.position.set(...position);
  134. + scene.add(light);
  135. + scene.add(light.target);
  136. +}
  137. +addLight([-3, 1, 1]);
  138. +addLight([ 2, 1, .5]);
  139. </pre>
  140. <p>2Dキャンバスを使い、ラベルを作るコードを作ってみましょう。</p>
  141. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function makeLabelCanvas(size, name) {
  142. + const borderSize = 2;
  143. + const ctx = document.createElement('canvas').getContext('2d');
  144. + const font = `${size}px bold sans-serif`;
  145. + ctx.font = font;
  146. + // measure how long the name will be
  147. + const doubleBorderSize = borderSize * 2;
  148. + const width = ctx.measureText(name).width + doubleBorderSize;
  149. + const height = size + doubleBorderSize;
  150. + ctx.canvas.width = width;
  151. + ctx.canvas.height = height;
  152. +
  153. + // need to set font again after resizing canvas
  154. + ctx.font = font;
  155. + ctx.textBaseline = 'top';
  156. +
  157. + ctx.fillStyle = 'blue';
  158. + ctx.fillRect(0, 0, width, height);
  159. + ctx.fillStyle = 'white';
  160. + ctx.fillText(name, borderSize, borderSize);
  161. +
  162. + return ctx.canvas;
  163. +}
  164. </pre>
  165. <p>続いて体はシリンダー、頭はスフィア、ラベルはプレーンを使い簡単なキャラクターを作ります。</p>
  166. <p>まずは共有のジオメトリを作ってみましょう。</p>
  167. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const bodyRadiusTop = .4;
  168. +const bodyRadiusBottom = .2;
  169. +const bodyHeight = 2;
  170. +const bodyRadialSegments = 6;
  171. +const bodyGeometry = new THREE.CylinderGeometry(
  172. + bodyRadiusTop, bodyRadiusBottom, bodyHeight, bodyRadialSegments);
  173. +
  174. +const headRadius = bodyRadiusTop * 0.8;
  175. +const headLonSegments = 12;
  176. +const headLatSegments = 5;
  177. +const headGeometry = new THREE.SphereGeometry(
  178. + headRadius, headLonSegments, headLatSegments);
  179. +
  180. +const labelGeometry = new THREE.PlaneGeometry(1, 1);
  181. </pre>
  182. <p>では、これらのパーツからキャラクターを作る機能を作ってみましょう。</p>
  183. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function makePerson(x, size, name, color) {
  184. + const canvas = makeLabelCanvas(size, name);
  185. + const texture = new THREE.CanvasTexture(canvas);
  186. + // because our canvas is likely not a power of 2
  187. + // in both dimensions set the filtering appropriately.
  188. + texture.minFilter = THREE.LinearFilter;
  189. + texture.wrapS = THREE.ClampToEdgeWrapping;
  190. + texture.wrapT = THREE.ClampToEdgeWrapping;
  191. +
  192. + const labelMaterial = new THREE.MeshBasicMaterial({
  193. + map: texture,
  194. + side: THREE.DoubleSide,
  195. + transparent: true,
  196. + });
  197. + const bodyMaterial = new THREE.MeshPhongMaterial({
  198. + color,
  199. + flatShading: true,
  200. + });
  201. +
  202. + const root = new THREE.Object3D();
  203. + root.position.x = x;
  204. +
  205. + const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
  206. + root.add(body);
  207. + body.position.y = bodyHeight / 2;
  208. +
  209. + const head = new THREE.Mesh(headGeometry, bodyMaterial);
  210. + root.add(head);
  211. + head.position.y = bodyHeight + headRadius * 1.1;
  212. +
  213. + const label = new THREE.Mesh(labelGeometry, labelMaterial);
  214. + root.add(label);
  215. + label.position.y = bodyHeight * 4 / 5;
  216. + label.position.z = bodyRadiusTop * 1.01;
  217. +
  218. + // if units are meters then 0.01 here makes size
  219. + // of the label into centimeters.
  220. + const labelBaseScale = 0.01;
  221. + label.scale.x = canvas.width * labelBaseScale;
  222. + label.scale.y = canvas.height * labelBaseScale;
  223. +
  224. + scene.add(root);
  225. + return root;
  226. +}
  227. </pre>
  228. <p>上記のようにルートの <a href="/docs/#api/ja/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> に体、頭、ラベルを配置して位置を調整しています。
  229. これでキャラクターを移動させたい場合、ルートオブジェクトを移動します。
  230. 体の高さは2です。
  231. 1が1メートルに等しい場合、上記のコードはラベルをcm単位で作成してます。
  232. 背の高さがcmのサイズなのでテキストに合うような幅が必要です。</p>
  233. <p>あとはラベルでキャラクターを作ればいいです。</p>
  234. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+makePerson(-3, 32, 'Purple People Eater', 'purple');
  235. +makePerson(-0, 32, 'Green Machine', 'green');
  236. +makePerson(+3, 32, 'Red Menace', 'red');
  237. </pre>
  238. <p>残作業はカメラを動かせるように <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> を追加します。</p>
  239. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from 'three';
  240. +import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
  241. </pre>
  242. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const fov = 75;
  243. const aspect = 2; // the canvas default
  244. const near = 0.1;
  245. -const far = 5;
  246. +const far = 50;
  247. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  248. -camera.position.z = 2;
  249. +camera.position.set(0, 2, 5);
  250. +const controls = new OrbitControls(camera, canvas);
  251. +controls.target.set(0, 2, 0);
  252. +controls.update();
  253. </pre>
  254. <p>そして、簡単なラベルを取得します。</p>
  255. <p></p><div translate="no" class="threejs_example_container notranslate">
  256. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-textured-labels.html"></iframe></div>
  257. <a class="threejs_center" href="/manual/examples/canvas-textured-labels.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  258. </div>
  259. <p></p>
  260. <p>気になる点がいくつかあります。</p>
  261. <ul>
  262. <li>拡大するとラベルがかなり低解像度になる</li>
  263. </ul>
  264. <p>簡単な解決策はありません。
  265. もっと複雑なフォントの描画テクニックがありますが、私は解決策を知りません。
  266. また、フォントデータをダウンロードするので時間がかかります。</p>
  267. <p>解決策の1つはラベルの解像度を上げる事です。
  268. 渡されたサイズを現在の2倍に設定し、<code class="notranslate" translate="no">labelBaseScale</code> を現在の半分に設定してみて下さい。</p>
  269. <ul>
  270. <li>名前が長いほどラベルが長くなります</li>
  271. </ul>
  272. <p>これを修正したければ代わりに固定サイズのラベルを貼り、テキストを押しつぶします。</p>
  273. <p>これはとても簡単です。基本となる幅を渡し、幅に合わせてテキストを拡大縮小します。</p>
  274. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function makeLabelCanvas(size, name) {
  275. +function makeLabelCanvas(baseWidth, size, name) {
  276. const borderSize = 2;
  277. const ctx = document.createElement('canvas').getContext('2d');
  278. const font = `${size}px bold sans-serif`;
  279. ctx.font = font;
  280. // measure how long the name will be
  281. + const textWidth = ctx.measureText(name).width;
  282. const doubleBorderSize = borderSize * 2;
  283. - const width = ctx.measureText(name).width + doubleBorderSize;
  284. + const width = baseWidth + doubleBorderSize;
  285. const height = size + doubleBorderSize;
  286. ctx.canvas.width = width;
  287. ctx.canvas.height = height;
  288. // need to set font again after resizing canvas
  289. ctx.font = font;
  290. - ctx.textBaseline = 'top';
  291. + ctx.textBaseline = 'middle';
  292. + ctx.textAlign = 'center';
  293. ctx.fillStyle = 'blue';
  294. ctx.fillRect(0, 0, width, height);
  295. + // scale to fit but don't stretch
  296. + const scaleFactor = Math.min(1, baseWidth / textWidth);
  297. + ctx.translate(width / 2, height / 2);
  298. + ctx.scale(scaleFactor, 1);
  299. ctx.fillStyle = 'white';
  300. ctx.fillText(name, borderSize, borderSize);
  301. return ctx.canvas;
  302. }
  303. </pre>
  304. <p>次にラベルの幅を渡します。</p>
  305. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function makePerson(x, size, name, color) {
  306. - const canvas = makeLabelCanvas(size, name);
  307. +function makePerson(x, labelWidth, size, name, color) {
  308. + const canvas = makeLabelCanvas(labelWidth, size, name);
  309. ...
  310. }
  311. -makePerson(-3, 32, 'Purple People Eater', 'purple');
  312. -makePerson(-0, 32, 'Green Machine', 'green');
  313. -makePerson(+3, 32, 'Red Menace', 'red');
  314. +makePerson(-3, 150, 32, 'Purple People Eater', 'purple');
  315. +makePerson(-0, 150, 32, 'Green Machine', 'green');
  316. +makePerson(+3, 150, 32, 'Red Menace', 'red');
  317. </pre>
  318. <p>テキストが中央揃えのラベルを取得し、それに合わせて拡大縮小されています。</p>
  319. <p></p><div translate="no" class="threejs_example_container notranslate">
  320. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-textured-labels-scale-to-fit.html"></iframe></div>
  321. <a class="threejs_center" href="/manual/examples/canvas-textured-labels-scale-to-fit.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  322. </div>
  323. <p></p>
  324. <p>上記ではそれぞれのテクスチャに新しいキャンバスを使用しました。
  325. テクスチャごとにキャンバスを使うかはあなた次第です。
  326. 頻繁に更新する必要がある場合は、テクスチャごとに1つのキャンバスを使用するのがベストな選択かもしれません。</p>
  327. <p>めったに更新されない場合は、Three.jsで強制的にテクスチャを使用し、1つのキャンバスを複数のテクスチャに使用できます。</p>
  328. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const ctx = document.createElement('canvas').getContext('2d');
  329. function makeLabelCanvas(baseWidth, size, name) {
  330. const borderSize = 2;
  331. - const ctx = document.createElement('canvas').getContext('2d');
  332. const font = `${size}px bold sans-serif`;
  333. ...
  334. }
  335. +const forceTextureInitialization = function() {
  336. + const material = new THREE.MeshBasicMaterial();
  337. + const geometry = new THREE.PlaneGeometry();
  338. + const scene = new THREE.Scene();
  339. + scene.add(new THREE.Mesh(geometry, material));
  340. + const camera = new THREE.Camera();
  341. +
  342. + return function forceTextureInitialization(texture) {
  343. + material.map = texture;
  344. + renderer.render(scene, camera);
  345. + };
  346. +}();
  347. function makePerson(x, labelWidth, size, name, color) {
  348. const canvas = makeLabelCanvas(labelWidth, size, name);
  349. const texture = new THREE.CanvasTexture(canvas);
  350. // because our canvas is likely not a power of 2
  351. // in both dimensions set the filtering appropriately.
  352. texture.minFilter = THREE.LinearFilter;
  353. texture.wrapS = THREE.ClampToEdgeWrapping;
  354. texture.wrapT = THREE.ClampToEdgeWrapping;
  355. + forceTextureInitialization(texture);
  356. ...
  357. </pre>
  358. <p></p><div translate="no" class="threejs_example_container notranslate">
  359. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-textured-labels-one-canvas.html"></iframe></div>
  360. <a class="threejs_center" href="/manual/examples/canvas-textured-labels-one-canvas.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  361. </div>
  362. <p></p>
  363. <p>もう1つの問題はラベルが常にカメラに向いているとは限らない事です。
  364. ラベルをバッジにしているなら、それは良い事なのかもしれません。
  365. 3Dゲームでプレイヤーの上に名前を置くためにラベルを使用している場合は、ラベルが常にカメラの方を向くようにしたいかもしれません。
  366. その方法は<a href="billboards.html">ビルボードの記事</a>で取り上げます。</p>
  367. <p>特にラベルの場合は<a href="align-html-elements-to-3d.html">もう1つの解決策はHTMLを使う事です</a>。
  368. この記事のラベルは他のオブジェクトで隠したい場合には良いですが、<a href="align-html-elements-to-3d.html">HTMLラベル</a>は常に上にあります。</p>
  369. </div>
  370. </div>
  371. </div>
  372. <script src="../resources/prettify.js"></script>
  373. <script src="../resources/lesson.js"></script>
  374. </body></html>