canvas-textures.html 19 KB

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