canvas-textures.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <!DOCTYPE html><html lang="zh"><head>
  2. <meta charset="utf-8">
  3. <title>Canvas 纹理</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 – Canvas Textures">
  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. <link rel="stylesheet" href="/manual/zh/lang.css">
  21. </head>
  22. <body>
  23. <div class="container">
  24. <div class="lesson-title">
  25. <h1>Canvas 纹理</h1>
  26. </div>
  27. <div class="lesson">
  28. <div class="lesson-main">
  29. <p>这篇文章是此篇 <a href="textures.html">关于纹理</a> 文章的延续,如果你还没有读过,你或许应当从那篇开始。</p>
  30. <p>在<a href="textures.html">上一篇讲解纹理的文章中</a>,我们主要使用图像文件来生成动态纹理,有时候我们想在运行时生成一个纹理。一种可行的方式是使用 <a href="/docs/#api/en/textures/CanvasTexture"><code class="notranslate" translate="no">CanvasTexture</code></a>。</p>
  31. <p>Canvas纹理 使用一个<code class="notranslate" translate="no">&lt;canvas&gt;</code> 作为它的输入, 如果你还不知道如何使用2D Canvas API来在画布上绘制内容,<a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial">MDN上有一篇很好的文章</a>。</p>
  32. <p>我们来写一段简单的Canvas代码,这是一个在随机位置上绘制随机颜色的点的程序。</p>
  33. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const ctx = document.createElement('canvas').getContext('2d');
  34. document.body.appendChild(ctx.canvas);
  35. ctx.canvas.width = 256;
  36. ctx.canvas.height = 256;
  37. ctx.fillStyle = '#FFF';
  38. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  39. function randInt(min, max) {
  40. if (max === undefined) {
  41. max = min;
  42. min = 0;
  43. }
  44. return Math.random() * (max - min) + min | 0;
  45. }
  46. function drawRandomDot() {
  47. ctx.fillStyle = `#${randInt(0x1000000).toString(16).padStart(6, '0')}`;
  48. ctx.beginPath();
  49. const x = randInt(256);
  50. const y = randInt(256);
  51. const radius = randInt(10, 64);
  52. ctx.arc(x, y, radius, 0, Math.PI * 2);
  53. ctx.fill();
  54. }
  55. function render() {
  56. drawRandomDot();
  57. requestAnimationFrame(render);
  58. }
  59. requestAnimationFrame(render);</pre>
  60. <p>这实在太简单了。</p>
  61. <p></p><div translate="no" class="threejs_example_container notranslate">
  62. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-random-dots.html"></iframe></div>
  63. <a class="threejs_center" href="/manual/examples/canvas-random-dots.html" target="_blank">点击在新窗口打开</a>
  64. </div>
  65. <p></p>
  66. <p>现在让我们用它来绘制纹理。我们会用从 <a href="textures.html">上一篇文章</a> 中绘制立方体纹理的例子开始。
  67. 我们将删除加载图像的代码,取而代之的是使用我们的Canvas,通过创建一个<a href="/docs/#api/en/textures/CanvasTexture"><code class="notranslate" translate="no">CanvasTexture</code></a>,然后把我们创建好的Canvas对象传入。</p>
  68. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const 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); // 添加到cube list中方便旋转</pre>
  84. <p>然后调用代码,在我们的渲染循环中绘制一个随机点。</p>
  85. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render(time) {
  86. time *= 0.001;
  87. if (resizeRendererToDisplaySize(renderer)) {
  88. const canvas = renderer.domElement;
  89. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  90. camera.updateProjectionMatrix();
  91. }
  92. + drawRandomDot();
  93. + texture.needsUpdate = true;
  94. cubes.forEach((cube, ndx) =&gt; {
  95. const speed = .2 + ndx * .1;
  96. const rot = time * speed;
  97. cube.rotation.x = rot;
  98. cube.rotation.y = rot;
  99. });
  100. renderer.render(scene, camera);
  101. requestAnimationFrame(render);
  102. }</pre>
  103. <p>我们只需要做额外的一件事,设置了 <a href="/docs/#api/en/textures/CanvasTexture"><code class="notranslate" translate="no">CanvasTexture</code></a> 的 <code class="notranslate" translate="no">needsUpdate</code>属性来告诉THREE.js来更新纹理画布的最新内容。</p>
  104. <p>这样,我们就有了一个用Canvas绘制纹理的立方体。</p>
  105. <p></p><div translate="no" class="threejs_example_container notranslate">
  106. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-textured-cube.html"></iframe></div>
  107. <a class="threejs_center" href="/manual/examples/canvas-textured-cube.html" target="_blank">点击在新窗口打开</a>
  108. </div>
  109. <p></p>
  110. <p>请注意,如果你想使用THREE.js绘制到Canvas中,你最好用 <code class="notranslate" translate="no">RenderTarget</code>,在 <a href="rendertargets.html">这篇文章</a> 中有提到。</p>
  111. <p>纹理画布的一个常见用法是在场景中绘制文本。例如,你想把一个人的名字放在他们角色上面作为一个徽标(Badge),你也许需要使用Canvas来绘制徽标纹理。</p>
  112. <p>让我们创建一个有3个人的场景,并给每个人绘制一个徽标或者标签(Label)。</p>
  113. <p>让我们用上面的例子,移除所有相关的立方体。然后设置背景为白色,然后添加两个<a href="lights.html">灯光</a>。</p>
  114. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  115. +scene.background = new THREE.Color('white');
  116. +
  117. +function addLight(position) {
  118. + const color = 0xFFFFFF;
  119. + const intensity = 1;
  120. + const light = new THREE.DirectionalLight(color, intensity);
  121. + light.position.set(...position);
  122. + scene.add(light);
  123. + scene.add(light.target);
  124. +}
  125. +addLight([-3, 1, 1]);
  126. +addLight([ 2, 1, .5]);</pre>
  127. <p>让我们写一些代码以使用2D Canvas绘制标签</p>
  128. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function makeLabelCanvas(size, name) {
  129. + const borderSize = 2;
  130. + const ctx = document.createElement('canvas').getContext('2d');
  131. + const font = `${size}px bold sans-serif`;
  132. + ctx.font = font;
  133. + // 测量一下name有多长
  134. + const doubleBorderSize = borderSize * 2;
  135. + const width = ctx.measureText(name).width + doubleBorderSize;
  136. + const height = size + doubleBorderSize;
  137. + ctx.canvas.width = width;
  138. + ctx.canvas.height = height;
  139. +
  140. + // 注意,调整画布后需要重新修改字体
  141. + ctx.font = font;
  142. + ctx.textBaseline = 'top';
  143. +
  144. + ctx.fillStyle = 'blue';
  145. + ctx.fillRect(0, 0, width, height);
  146. + ctx.fillStyle = 'white';
  147. + ctx.fillText(name, borderSize, borderSize);
  148. +
  149. + return ctx.canvas;
  150. +}</pre>
  151. <p>然后我们将用一个圆柱体作为身体,一个球体作为头部,一个平面作为标签来制作一个简单的人。</p>
  152. <p>首先我们开始制作共享几何体。</p>
  153. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const bodyRadiusTop = .4;
  154. +const bodyRadiusBottom = .2;
  155. +const bodyHeight = 2;
  156. +const bodyRadialSegments = 6;
  157. +const bodyGeometry = new THREE.CylinderGeometry(
  158. + bodyRadiusTop, bodyRadiusBottom, bodyHeight, bodyRadialSegments);
  159. +
  160. +const headRadius = bodyRadiusTop * 0.8;
  161. +const headLonSegments = 12;
  162. +const headLatSegments = 5;
  163. +const headGeometry = new THREE.SphereGeometry(
  164. + headRadius, headLonSegments, headLatSegments);
  165. +
  166. +const labelGeometry = new THREE.PlaneGeometry(1, 1);</pre>
  167. <p>然后我们写一个函数把这些部分组合成一个人。</p>
  168. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function makePerson(x, size, name, color) {
  169. + const canvas = makeLabelCanvas(size, name);
  170. + const texture = new THREE.CanvasTexture(canvas);
  171. + // 因为我们的Canvas长宽都不太可能是2的倍数,所以将filtering设置合理一些
  172. + texture.minFilter = THREE.LinearFilter;
  173. + texture.wrapS = THREE.ClampToEdgeWrapping;
  174. + texture.wrapT = THREE.ClampToEdgeWrapping;
  175. +
  176. + const labelMaterial = new THREE.MeshBasicMaterial({
  177. + map: texture,
  178. + side: THREE.DoubleSide,
  179. + transparent: true,
  180. + });
  181. + const bodyMaterial = new THREE.MeshPhongMaterial({
  182. + color,
  183. + flatShading: true,
  184. + });
  185. +
  186. + const root = new THREE.Object3D();
  187. + root.position.x = x;
  188. +
  189. + const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
  190. + root.add(body);
  191. + body.position.y = bodyHeight / 2;
  192. +
  193. + const head = new THREE.Mesh(headGeometry, bodyMaterial);
  194. + root.add(head);
  195. + head.position.y = bodyHeight + headRadius * 1.1;
  196. +
  197. + const label = new THREE.Mesh(labelGeometry, labelMaterial);
  198. + root.add(label);
  199. + label.position.y = bodyHeight * 4 / 5;
  200. + label.position.z = bodyRadiusTop * 1.01;
  201. +
  202. + // 如果单位是米, 那这里0.01就是将标签的尺寸转化为厘米
  203. + const labelBaseScale = 0.01;
  204. + label.scale.x = canvas.width * labelBaseScale;
  205. + label.scale.y = canvas.height * labelBaseScale;
  206. +
  207. + scene.add(root);
  208. + return root;
  209. +}</pre>
  210. <p>在上面你可以看到,我们把身体、头部、标签放在了一个根<a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> 上并且调整了他们的位置。这样如果我们想移动人的话直接移动根对象就可以了。身体是2个单位的高度,如果1个单位等于1米,那么上面的代码会尝试用厘米为单位制作标签,它们使用厘米作为宽高,以更好的适合文本。</p>
  211. <p>然后我们可以制作带标签的人</p>
  212. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+makePerson(-3, 32, 'Purple People Eater', 'purple');
  213. +makePerson(-0, 32, 'Green Machine', 'green');
  214. +makePerson(+3, 32, 'Red Menace', 'red');</pre>
  215. <p>剩下的就是添加 <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> 这样我们就可以移动相机了。</p>
  216. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from 'three';
  217. +import {OrbitControls} from 'three/addons/controls/OrbitControls.js';</pre>
  218. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const fov = 75;
  219. const aspect = 2; // Canvas默认值
  220. const near = 0.1;
  221. -const far = 5;
  222. +const far = 50;
  223. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  224. -camera.position.z = 2;
  225. +camera.position.set(0, 2, 5);
  226. +const controls = new OrbitControls(camera, canvas);
  227. +controls.target.set(0, 2, 0);
  228. +controls.update();</pre>
  229. <p>然后我们得到了一些简单的标签。</p>
  230. <p></p><div translate="no" class="threejs_example_container notranslate">
  231. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/canvas-textured-labels.html"></iframe></div>
  232. <a class="threejs_center" href="/manual/examples/canvas-textured-labels.html" target="_blank">点击在新窗口打开</a>
  233. </div>
  234. <p></p>
  235. <p>注意事项:</p>
  236. <ul>
  237. <li>如果你过度放大,标签的分辨率会降低。</li>
  238. </ul>
  239. <p>没有简单的解决方案,还有更复杂的字体渲染技术,据我所知没有插件可以解决这个问题。另外,还需要用户下载字体数据文件,这会变得很慢。</p>
  240. <p>一种方案是增加标签的分辨率,尝试让尺寸变成现在的2倍,然后设置 <code class="notranslate" translate="no">labelBaseScale</code> 是现在的一半。</p>
  241. <ul>
  242. <li>名字越长,标签越长。</li>
  243. </ul>
  244. <p>如果你想解决这个问题,你需要指定标签的固定大小,然后挤压文本。</p>
  245. <p>这很容易做到。传入一个基本宽度并缩放文本以适应。</p>
  246. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function makeLabelCanvas(size, name) {
  247. +function makeLabelCanvas(baseWidth, size, name) {
  248. const borderSize = 2;
  249. const ctx = document.createElement('canvas').getContext('2d');
  250. const font = `${size}px bold sans-serif`;
  251. ctx.font = font;
  252. // 测量一下name有多长
  253. + const textWidth = ctx.measureText(name).width;
  254. const doubleBorderSize = borderSize * 2;
  255. - const width = ctx.measureText(name).width + doubleBorderSize;
  256. + const width = baseWidth + doubleBorderSize;
  257. const height = size + doubleBorderSize;
  258. ctx.canvas.width = width;
  259. ctx.canvas.height = height;
  260. // 注意,调整画布后需要重新修改字体
  261. ctx.font = font;
  262. - ctx.textBaseline = 'top';
  263. + ctx.textBaseline = 'middle';
  264. + ctx.textAlign = 'center';
  265. ctx.fillStyle = 'blue';
  266. ctx.fillRect(0, 0, width, height);
  267. + // 缩放以适应,但是不要拉伸
  268. + const scaleFactor = Math.min(1, baseWidth / textWidth);
  269. + ctx.translate(width / 2, height / 2);
  270. + ctx.scale(scaleFactor, 1);
  271. ctx.fillStyle = 'white';
  272. ctx.fillText(name, borderSize, borderSize);
  273. return ctx.canvas;
  274. }</pre>
  275. <p>然后我们可以传入预期标签的长度</p>
  276. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function makePerson(x, size, name, color) {
  277. - const canvas = makeLabelCanvas(size, name);
  278. +function makePerson(x, labelWidth, size, name, color) {
  279. + const canvas = makeLabelCanvas(labelWidth, size, name);
  280. ...
  281. }
  282. -makePerson(-3, 32, 'Purple People Eater', 'purple');
  283. -makePerson(-0, 32, 'Green Machine', 'green');
  284. -makePerson(+3, 32, 'Red Menace', 'red');
  285. +makePerson(-3, 150, 32, 'Purple People Eater', 'purple');
  286. +makePerson(-0, 150, 32, 'Green Machine', 'green');
  287. +makePerson(+3, 150, 32, 'Red Menace', 'red');</pre>
  288. <p>我们将文本居中并缩放以适应标签的尺寸。</p>
  289. <p></p><div translate="no" class="threejs_example_container notranslate">
  290. <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>
  291. <a class="threejs_center" href="/manual/examples/canvas-textured-labels-scale-to-fit.html" target="_blank">点击在新窗口打开</a>
  292. </div>
  293. <p></p>
  294. <p>上面我们为每一个纹理使用了单独的Canvas,是否为每个纹理使用单独的Canvas取决于你。如果你需要经常单独更新它们,每个纹理一个Canvas是一个比较好的选择。如果它们很少或者从不更新,那么你可以用一个Canvas,通过THREE.js来生成多个纹理。让我们更改上面的代码来完成这一点。</p>
  295. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const ctx = document.createElement('canvas').getContext('2d');
  296. function makeLabelCanvas(baseWidth, size, name) {
  297. const borderSize = 2;
  298. - const ctx = document.createElement('canvas').getContext('2d');
  299. const font = `${size}px bold sans-serif`;
  300. ...
  301. }
  302. +const forceTextureInitialization = function() {
  303. + const material = new THREE.MeshBasicMaterial();
  304. + const geometry = new THREE.PlaneGeometry();
  305. + const scene = new THREE.Scene();
  306. + scene.add(new THREE.Mesh(geometry, material));
  307. + const camera = new THREE.Camera();
  308. +
  309. + return function forceTextureInitialization(texture) {
  310. + material.map = texture;
  311. + renderer.render(scene, camera);
  312. + };
  313. +}();
  314. function makePerson(x, labelWidth, size, name, color) {
  315. const canvas = makeLabelCanvas(labelWidth, size, name);
  316. const texture = new THREE.CanvasTexture(canvas);
  317. // 因为我们的Canvas长宽都不太可能是2的倍数,所以将filtering设置合理一些
  318. texture.minFilter = THREE.LinearFilter;
  319. texture.wrapS = THREE.ClampToEdgeWrapping;
  320. texture.wrapT = THREE.ClampToEdgeWrapping;
  321. + forceTextureInitialization(texture);
  322. ...</pre>
  323. <p></p><div translate="no" class="threejs_example_container notranslate">
  324. <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>
  325. <a class="threejs_center" href="/manual/examples/canvas-textured-labels-one-canvas.html" target="_blank">点击在新窗口打开</a>
  326. </div>
  327. <p></p>
  328. <p>另一个问题是标签并不总是面向相机,如果你使用标签作为徽标,这可能是一件好事。
  329. 如果你使用标签来放置3D游戏中玩家的名字,也许你希望标签总是面对相机。
  330. 具体内容在 <a href="billboards.html">广告牌(Billboards)文章</a> 有覆盖到。</p>
  331. <p>特别是对于标签,<a href="align-html-elements-to-3d.html">另一种解决方案是使用HTML</a>,
  332. 本文中的标签是 <em>位于3D场景中</em> ,如果你想要他们被其他对象遮挡是很好的,因为 <a href="align-html-elements-to-3d.html">HTML 标签</a> 总是在最上层。
  333. </p>
  334. </div>
  335. </div>
  336. </div>
  337. <script src="../resources/prettify.js"></script>
  338. <script src="../resources/lesson.js"></script>
  339. </body></html>