responsive.html 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. Title: Three.js Responsive Design
  2. Description: How to make your three.js fit different sized displays.
  3. TOC: Responsive Design
  4. This is the second article in a series of articles about three.js.
  5. The first article was [about fundamentals](threejs-fundamentals.html).
  6. If you haven't read that yet you might want to start there.
  7. This article is about how to make your three.js app be responsive
  8. to any situation. Making a webpage responsive generally refers
  9. to the page displaying well on different sized displays from
  10. desktops to tablets to phones.
  11. For three.js there are even more situations to consider. For
  12. example, a 3D editor with controls on the left, right, top, or
  13. bottom is something we might want to handle. A live diagram
  14. in the middle of a document is another example.
  15. The last sample we had used a plain canvas with no CSS and
  16. no size
  17. ```html
  18. <canvas id="c"></canvas>
  19. ```
  20. That canvas defaults to 300x150 CSS pixels in size.
  21. In the web platform the recommended way to set the size
  22. of something is to use CSS.
  23. Let's make the canvas fill the page by adding CSS
  24. ```html
  25. <style>
  26. html, body {
  27. margin: 0;
  28. height: 100%;
  29. }
  30. #c {
  31. width: 100%;
  32. height: 100%;
  33. display: block;
  34. }
  35. </style>
  36. ```
  37. In HTML the body has a margin of 5 pixels by default so setting the
  38. margin to 0 removes the margin. Setting the html and body height to 100%
  39. makes them fill the window. Otherwise they are only as large
  40. as the content that fills them.
  41. Next we tell the `id=c` element to be
  42. 100% the size of its container which in this case is the body of
  43. the document.
  44. Finally we set its `display` mode to `block`. A canvas's
  45. default display mode is `inline`. Inline
  46. elements can end up adding whitespace to what is displayed. By
  47. setting the canvas to `block` that issue goes away.
  48. Here's the result
  49. {{{example url="../threejs-responsive-no-resize.html" }}}
  50. You can see the canvas is now filling the page but there are 2
  51. problems. One our cubes are stretched. They are not cubes they
  52. are more like boxes. Too tall or too wide. Open the
  53. example in its own window and resize it. You'll see how
  54. the cubes get stretched wide and tall.
  55. <img src="resources/images/resize-incorrect-aspect.png" width="407" class="threejs_center nobg">
  56. The second problem is they look low resolution or blocky and
  57. blurry. Stretch the window really large and you'll really see
  58. the issue.
  59. <img src="resources/images/resize-low-res.png" class="threejs_center nobg">
  60. Let's fix the stretchy problem first. To do that we need
  61. to set the aspect of the camera to the aspect of the canvas's
  62. display size. We can do that by looking at the canvas's
  63. `clientWidth` and `clientHeight` properties.
  64. We'll update our render loop like this
  65. ```js
  66. function render(time) {
  67. time *= 0.001;
  68. + const canvas = renderer.domElement;
  69. + camera.aspect = canvas.clientWidth / canvas.clientHeight;
  70. + camera.updateProjectionMatrix();
  71. ...
  72. ```
  73. Now the cubes should stop being distorted.
  74. {{{example url="../threejs-responsive-update-camera.html" }}}
  75. Open the example in a separate window and resize the window
  76. and you should see the cubes are no longer stretched tall or wide.
  77. They stay the correct aspect regardless of window size.
  78. <img src="resources/images/resize-correct-aspect.png" width="407" class="threejs_center nobg">
  79. Now let's fix the blockiness.
  80. Canvas elements have 2 sizes. One size is the size the canvas is displayed
  81. on the page. That's what we set with CSS. The other size is the
  82. number of pixels in the canvas itself. This is no different than an image.
  83. For example we might have a 128x64 pixel image and using
  84. CSS we might display as 400x200 pixels.
  85. ```html
  86. <img src="some128x64image.jpg" style="width:400px; height:200px">
  87. ```
  88. A canvas's internal size, its resolution, is often called its drawingbuffer size.
  89. In three.js we can set the canvas's drawingbuffer size by calling `renderer.setSize`.
  90. What size should we pick? The most obvious answer is "the same size the canvas is displayed".
  91. Again, to do that we can look at the canvas's `clientWidth` and `clientHeight`
  92. properties.
  93. Let's write a function that checks if the renderer's canvas is not
  94. already the size it is being displayed as and if so set its size.
  95. ```js
  96. function resizeRendererToDisplaySize(renderer) {
  97. const canvas = renderer.domElement;
  98. const width = canvas.clientWidth;
  99. const height = canvas.clientHeight;
  100. const needResize = canvas.width !== width || canvas.height !== height;
  101. if (needResize) {
  102. renderer.setSize(width, height, false);
  103. }
  104. return needResize;
  105. }
  106. ```
  107. Notice we check if the canvas actually needs to be resized. Resizing the canvas
  108. is an interesting part of the canvas spec and it's best not to set the same
  109. size if it's already the size we want.
  110. Once we know if we need to resize or not we then call `renderer.setSize` and
  111. pass in the new width and height. It's important to pass `false` at the end.
  112. `render.setSize` by default sets the canvas's CSS size but doing so is not
  113. what we want. We want the browser to continue to work how it does for all other
  114. elements which is to use CSS to determine the display size of the element. We don't
  115. want canvases used by three to be different than other elements.
  116. Note that our function returns true if the canvas was resized. We can use
  117. this to check if there are other things we should update. Let's modify
  118. our render loop to use the new function
  119. ```js
  120. function render(time) {
  121. time *= 0.001;
  122. + if (resizeRendererToDisplaySize(renderer)) {
  123. + const canvas = renderer.domElement;
  124. + camera.aspect = canvas.clientWidth / canvas.clientHeight;
  125. + camera.updateProjectionMatrix();
  126. + }
  127. ...
  128. ```
  129. Since the aspect is only going to change if the canvas's display size
  130. changed we only set the camera's aspect if `resizeRendererToDisplaySize`
  131. returns `true`.
  132. {{{example url="../threejs-responsive.html" }}}
  133. It should now render with a resolution that matches the display
  134. size of the canvas.
  135. To make the point about letting CSS handle the resizing let's take
  136. our code and put it in a [separate `.js` file](../threejs-responsive.js).
  137. Here then are a few more examples where we let CSS choose the size and notice we had
  138. to change zero code for them to work.
  139. Let's put our cubes in the middle of a paragraph of text.
  140. {{{example url="../threejs-responsive-paragraph.html" startPane="html" }}}
  141. and here's our same code used in an editor style layout
  142. where the control area on the right can be resized.
  143. {{{example url="../threejs-responsive-editor.html" startPane="html" }}}
  144. The important part to notice is no code changed. Only our HTML and CSS
  145. changed.
  146. ## Handling HD-DPI displays
  147. HD-DPI stands for high-density dot per inch displays.
  148. That's most Macs nowadays and many Windows machines
  149. as well as pretty much all smartphones.
  150. The way this works in the browser is they use
  151. CSS pixels to set the sizes which are supposed to be the same
  152. regardless of how high res the display is. The browser
  153. will just render text with more detail but the
  154. same physical size.
  155. There are various ways to handle HD-DPI with three.js.
  156. The first one is just not to do anything special. This
  157. is arguably the most common. Rendering 3D graphics
  158. takes a lot of GPU processing power. Mobile GPUs have
  159. less power than desktops, at least as of 2018, and yet
  160. mobile phones often have very high resolution displays.
  161. The current top of the line phones have an HD-DPI ratio
  162. of 3x meaning for every one pixel from a non-HD-DPI display
  163. those phones have 9 pixels. That means they have to do 9x
  164. the rendering.
  165. Computing 9x the pixels is a lot of work so if we just
  166. leave the code as it is we'll compute 1x the pixels and the
  167. browser will just draw it at 3x the size (3x by 3x = 9x pixels).
  168. For any heavy three.js app that's probably what you want
  169. otherwise you're likely to get a slow framerate.
  170. That said if you actually do want to render at the resolution
  171. of the device there are a couple of ways to do this in three.js.
  172. One is to tell three.js a resolution multiplier using `renderer.setPixelRatio`.
  173. You ask the browser what the multiplier is from CSS pixels to device pixels
  174. and pass that to three.js
  175. renderer.setPixelRatio(window.devicePixelRatio);
  176. After that any calls to `renderer.setSize` will magically
  177. use the size you request multiplied by whatever pixel ratio
  178. you passed in. **This is strongly NOT RECOMMENDED**. See below
  179. The other way is to do it yourself when you resize the canvas.
  180. ```js
  181. function resizeRendererToDisplaySize(renderer) {
  182. const canvas = renderer.domElement;
  183. const pixelRatio = window.devicePixelRatio;
  184. const width = canvas.clientWidth * pixelRatio | 0;
  185. const height = canvas.clientHeight * pixelRatio | 0;
  186. const needResize = canvas.width !== width || canvas.height !== height;
  187. if (needResize) {
  188. renderer.setSize(width, height, false);
  189. }
  190. return needResize;
  191. }
  192. ```
  193. This second way is objectively better. Why? Because it means I get what I ask for.
  194. There are many cases when using three.js where we need to know the actual
  195. size of the canvas's drawingBuffer. For example when making a post processing filter,
  196. or if we are making a shader that accesses `gl_FragCoord`, if we are making
  197. a screenshot, or reading pixels for GPU picking, for drawing into a 2D canvas,
  198. etc... There many many cases where if we use `setPixelRatio` then our actual size will be different
  199. than the size we requested and we'll have to guess when to use the size
  200. we asked for and when to use the size three.js is actually using.
  201. By doing it ourselves we always know the size being used is the size we requested.
  202. There is no special case where magic is happening behind the scenes.
  203. Here's an example using the code above.
  204. {{{example url="../threejs-responsive-hd-dpi.html" }}}
  205. It might be hard to see the difference but if you have an HD-DPI
  206. display and you compare this sample to those above you should
  207. notice the edges are more crisp.
  208. This article covered a very basic but fundamental topic. Next up lets quickly
  209. [go over the basic primitives that three.js provides](threejs-primitives.html).
粤ICP备19079148号