prerequisites.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Prerequisites</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 – Prerequisites">
  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>Prerequisites</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>These articles are meant to help you learn how to use three.js.
  29. They assume you know how to program in JavaScript. They assume
  30. you know what the DOM is, how to write HTML as well as create DOM elements
  31. in JavaScript. They assume you know how to use
  32. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">es6 modules</a>
  33. via import and via <code class="notranslate" translate="no">&lt;script type="module"&gt;</code> tags. They assume you know how to use import maps.
  34. They assume you know some CSS and that you know what
  35. <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors">CSS selectors are</a>.
  36. They also assume you know ES5, ES6 and maybe some ES7.
  37. They assume you know that the browser runs JavaScript only via events and callbacks.
  38. They assume you know what a closure is.</p>
  39. <p>Here's some brief refreshers and notes</p>
  40. <h2 id="es6-modules">es6 modules</h2>
  41. <p>es6 modules can be loaded via the <code class="notranslate" translate="no">import</code> keyword in a script
  42. or inline via a <code class="notranslate" translate="no">&lt;script type="module"&gt;</code> tag. Here's an example</p>
  43. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">
  44. &lt;script type="importmap"&gt;
  45. {
  46. "imports": {
  47. "three": "./path/to/three.module.js",
  48. "three/addons/": "./different/path/to/examples/jsm/"
  49. }
  50. }
  51. &lt;/script&gt;
  52. &lt;script type="module"&gt;
  53. import * as THREE from 'three';
  54. import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
  55. ...
  56. &lt;/script&gt;
  57. </pre>
  58. <p>See more details at the bottom of <a href="fundamentals.html">this article</a>.</p>
  59. <h2 id="-document-queryselector-and-document-queryselectorall-"><code class="notranslate" translate="no">document.querySelector</code> and <code class="notranslate" translate="no">document.querySelectorAll</code></h2>
  60. <p>You can use <code class="notranslate" translate="no">document.querySelector</code> to select the first element
  61. that matches a CSS selector. <code class="notranslate" translate="no">document.querySelectorAll</code> returns
  62. all elements that match a CSS selector.</p>
  63. <h2 id="you-don-t-need-onload-">You don't need <code class="notranslate" translate="no">onload</code></h2>
  64. <p>Lots of 20yr old pages use HTML like</p>
  65. <pre class="prettyprint showlinemods notranslate notranslate" translate="no">&lt;body onload="somefunction()"&gt;
  66. </pre><p>That style is deprecated. Put your scripts
  67. at the bottom of the page.</p>
  68. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;html&gt;
  69. &lt;head&gt;
  70. ...
  71. &lt;/head&gt;
  72. &lt;body&gt;
  73. ...
  74. &lt;/body&gt;
  75. &lt;script&gt;
  76. // inline javascript
  77. &lt;/script&gt;
  78. &lt;/html&gt;
  79. </pre>
  80. <p>or <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script">use the <code class="notranslate" translate="no">defer</code> property</a>.</p>
  81. <h2 id="know-how-closures-work">Know how closures work</h2>
  82. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function a(v) {
  83. const foo = v;
  84. return function() {
  85. return foo;
  86. };
  87. }
  88. const f = a(123);
  89. const g = a(456);
  90. console.log(f()); // prints 123
  91. console.log(g()); // prints 456
  92. </pre>
  93. <p>In the code above the function <code class="notranslate" translate="no">a</code> creates a new function every time it's called. That
  94. function <em>closes</em> over the variable <code class="notranslate" translate="no">foo</code>. Here's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">more info</a>.</p>
  95. <h2 id="understand-how-this-works">Understand how <code class="notranslate" translate="no">this</code> works</h2>
  96. <p><code class="notranslate" translate="no">this</code> is not magic. It's effectively a variable that is automatically passed to functions just like
  97. an argument is passed to function. The simple explanation is when you call a function directly
  98. like</p>
  99. <pre class="prettyprint showlinemods notranslate notranslate" translate="no">somefunction(a, b, c);
  100. </pre><p><code class="notranslate" translate="no">this</code> will be <code class="notranslate" translate="no">null</code> (when in strict mode or in a module) where as when you call a function via the dot operator <code class="notranslate" translate="no">.</code> like this</p>
  101. <pre class="prettyprint showlinemods notranslate notranslate" translate="no">someobject.somefunction(a, b, c);
  102. </pre><p><code class="notranslate" translate="no">this</code> will be set to <code class="notranslate" translate="no">someobject</code>.</p>
  103. <p>The parts where people get confused is with callbacks.</p>
  104. <pre class="prettyprint showlinemods notranslate notranslate" translate="no"> const callback = someobject.somefunction;
  105. loader.load(callback);
  106. </pre><p>doesn't work as someone inexperienced might expect because when
  107. <code class="notranslate" translate="no">loader.load</code> calls the callback it's not calling it with the dot <code class="notranslate" translate="no">.</code> operator
  108. so by default <code class="notranslate" translate="no">this</code> will be null (unless the loader explicitly sets it to something).
  109. If you want <code class="notranslate" translate="no">this</code> to be <code class="notranslate" translate="no">someobject</code> when the callback happens you need to
  110. tell JavaScript that by binding it to the function.</p>
  111. <pre class="prettyprint showlinemods notranslate notranslate" translate="no"> const callback = someobject.somefunction.bind(someobject);
  112. loader.load(callback);
  113. </pre><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this"><em>this</em> article might help explain <code class="notranslate" translate="no">this</code></a>.</p>
  114. <h2 id="es5-es6-es7-stuff">ES5/ES6/ES7 stuff</h2>
  115. <h3 id="-var-is-deprecated-use-const-and-or-let-"><code class="notranslate" translate="no">var</code> is deprecated. Use <code class="notranslate" translate="no">const</code> and/or <code class="notranslate" translate="no">let</code></h3>
  116. <p>There is no reason to use <code class="notranslate" translate="no">var</code> <strong>EVER</strong> and at this point it's considered bad practice
  117. to use it at all. Use <code class="notranslate" translate="no">const</code> if the variable will never be reassigned which is most of
  118. the time. Use <code class="notranslate" translate="no">let</code> in those cases where the value changes. This will help avoid tons of bugs.</p>
  119. <h3 id="use-for-elem-of-collection-never-for-elem-in-collection-">Use <code class="notranslate" translate="no">for(elem of collection)</code> never <code class="notranslate" translate="no">for(elem in collection)</code></h3>
  120. <p><code class="notranslate" translate="no">for of</code> is new, <code class="notranslate" translate="no">for in</code> is old. <code class="notranslate" translate="no">for in</code> had issues that are solved by <code class="notranslate" translate="no">for of</code></p>
  121. <p>As one example you can iterate over all the key/value pairs of an object with</p>
  122. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">for (const [key, value] of Object.entries(someObject)) {
  123. console.log(key, value);
  124. }
  125. </pre>
  126. <h3 id="use-foreach-map-and-filter-where-useful">Use <code class="notranslate" translate="no">forEach</code>, <code class="notranslate" translate="no">map</code>, and <code class="notranslate" translate="no">filter</code> where useful</h3>
  127. <p>Arrays added the functions <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach"><code class="notranslate" translate="no">forEach</code></a>,
  128. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"><code class="notranslate" translate="no">map</code></a>, and
  129. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter"><code class="notranslate" translate="no">filter</code></a> and
  130. are used fairly extensively in modern JavaScript.</p>
  131. <h3 id="use-destructuring">Use destructuring</h3>
  132. <p>Assume an object <code class="notranslate" translate="no">const dims = {width: 300, height: 150}</code></p>
  133. <p>old code</p>
  134. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const width = dims.width;
  135. const height = dims.height;
  136. </pre>
  137. <p>new code</p>
  138. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const {width, height} = dims;
  139. </pre>
  140. <p>Destructuring works with arrays too. Assume an array <code class="notranslate" translate="no">const position = [5, 6, 7, 1]</code>;</p>
  141. <p>old code</p>
  142. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const y = position[1];
  143. const z = position[2];
  144. </pre>
  145. <p>new code</p>
  146. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const [, y, z] = position;
  147. </pre>
  148. <p>Destructuring also works in function arguments</p>
  149. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const dims = {width: 300, height: 150};
  150. const vector = [3, 4];
  151. function lengthOfVector([x, y]) {
  152. return Math.sqrt(x * x + y * y);
  153. }
  154. const dist = lengthOfVector(vector); // dist = 5
  155. function area({width, height}) {
  156. return width * height;
  157. }
  158. const a = area(dims); // a = 45000
  159. </pre>
  160. <h3 id="use-object-declaration-short-cuts">Use object declaration short cuts</h3>
  161. <p>old code</p>
  162. <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> const width = 300;
  163. const height = 150;
  164. const obj = {
  165. width: width,
  166. height: height,
  167. area: function() {
  168. return this.width * this.height
  169. },
  170. };
  171. </pre>
  172. <p>new code</p>
  173. <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> const width = 300;
  174. const height = 150;
  175. const obj = {
  176. width,
  177. height,
  178. area() {
  179. return this.width * this.height;
  180. },
  181. };
  182. </pre>
  183. <h3 id="use-the-rest-parameter-and-the-spread-operator-">Use the rest parameter and the spread operator <code class="notranslate" translate="no">...</code></h3>
  184. <p>The rest parameter can be used to consume any number of parameters. Example</p>
  185. <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> function log(className, ...args) {
  186. const elem = document.createElement('div');
  187. elem.className = className;
  188. elem.textContent = args.join(' ');
  189. document.body.appendChild(elem);
  190. }
  191. </pre>
  192. <p>The spread operator can be used to expand an iterable into arguments</p>
  193. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const position = [1, 2, 3];
  194. someMesh.position.set(...position);
  195. </pre>
  196. <p>or copy an array</p>
  197. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const copiedPositionArray = [...position];
  198. copiedPositionArray.push(4); // [1,2,3,4]
  199. console.log(position); // [1,2,3] position is unaffected
  200. </pre>
  201. <p>or to merge objects</p>
  202. <pre class="prettyprint showlinemods notranslate notranslate" translate="no">const a = {abc: 123};
  203. const b = {def: 456};
  204. const c = {...a, ...b}; // c is now {abc: 123, def: 456}
  205. </pre><h3 id="use-class-">Use <code class="notranslate" translate="no">class</code></h3>
  206. <p>The syntax for making class like objects pre ES5 was unfamiliar to most
  207. programmers. As of ES5 you can now <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">use the <code class="notranslate" translate="no">class</code>
  208. keyword</a>
  209. which is closer to the style of C++/C#/Java.</p>
  210. <h3 id="understand-getters-and-setters">Understand getters and setters</h3>
  211. <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get">Getters</a> and
  212. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set">setters</a> are
  213. common in most modern languages. The <code class="notranslate" translate="no">class</code> syntax
  214. of ES5 makes them much easier than pre ES5.</p>
  215. <h3 id="use-arrow-functions-where-appropriate">Use arrow functions where appropriate</h3>
  216. <p>This is especially useful with callbacks and promises.</p>
  217. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">loader.load((texture) =&gt; {
  218. // use texture
  219. });
  220. </pre>
  221. <p>Arrow functions bind <code class="notranslate" translate="no">this</code> to the context in which you create the arrow function.</p>
  222. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const foo = (args) =&gt; {/* code */};
  223. </pre>
  224. <p>is a shortcut for</p>
  225. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const foo = (function(args) {/* code */}).bind(this));
  226. </pre>
  227. <p>See link above for more info on <code class="notranslate" translate="no">this</code>.</p>
  228. <h3 id="promises-as-well-as-async-await">Promises as well as async/await</h3>
  229. <p>Promises help with asynchronous code. Async/await help
  230. use promises.</p>
  231. <p>It's too big a topic to go into here but you can <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">read up
  232. on promises here</a>
  233. and <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await">async/await here</a>.</p>
  234. <h3 id="use-template-literals">Use Template Literals</h3>
  235. <p>Template literals are strings using backticks instead of quotes.</p>
  236. <pre class="prettyprint showlinemods notranslate notranslate" translate="no">const foo = `this is a template literal`;
  237. </pre><p>Template literals have basically 2 features. One is they can be multi-line</p>
  238. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const foo = `this
  239. is
  240. a
  241. template
  242. literal`;
  243. const bar = "this\nis\na\ntemplate\nliteral";
  244. </pre>
  245. <p><code class="notranslate" translate="no">foo</code> and <code class="notranslate" translate="no">bar</code> above are the same.</p>
  246. <p>The other is that you can pop out of string mode and insert snippets of
  247. JavaScript using <code class="notranslate" translate="no">${javascript-expression}</code>. This is the template part. Example:</p>
  248. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const r = 192;
  249. const g = 255;
  250. const b = 64;
  251. const rgbCSSColor = `rgb(${r},${g},${b})`;
  252. </pre>
  253. <p>or</p>
  254. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const color = [192, 255, 64];
  255. const rgbCSSColor = `rgb(${color.join(',')})`;
  256. </pre>
  257. <p>or</p>
  258. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const aWidth = 10;
  259. const bWidth = 20;
  260. someElement.style.width = `${aWidth + bWidth}px`;
  261. </pre>
  262. <h1 id="learn-javascript-coding-conventions-">Learn JavaScript coding conventions.</h1>
  263. <p>While you're welcome to format your code any way you chose there is at least one
  264. convention you should be aware of. Variables, function names, method names, in
  265. JavaScript are all lowerCasedCamelCase. Constructors, the names of classes are
  266. CapitalizedCamelCase. If you follow this rule you code will match most other
  267. JavaScript. Many <a href="https://eslint.org">linters</a>, programs that check for obvious errors in your code,
  268. will point out errors if you use the wrong case since by following the convention
  269. above they can know when you're using something incorrectly.</p>
  270. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const v = new vector(); // clearly an error if all classes start with a capital letter
  271. const v = Vector(); // clearly an error if all functions start with a lowercase letter.
  272. </pre>
  273. <h1 id="consider-using-visual-studio-code">Consider using Visual Studio Code</h1>
  274. <p>Of course use whatever editor you want but if you haven't tried it consider
  275. using <a href="https://code.visualstudio.com/">Visual Studio Code</a> for JavaScript and
  276. after installing it <a href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">setup
  277. eslint</a>.
  278. It might take a few minutes to setup but it will help you immensely with finding
  279. bugs in your JavaScript.</p>
  280. <p>Some examples</p>
  281. <p>If you enable <a href="https://eslint.org/docs/rules/no-undef">the <code class="notranslate" translate="no">no-undef</code> rule</a> then
  282. VSCode via ESLint will warn you of many undefined variables. </p>
  283. <div class="threejs_center"><img style="width: 615px;" src="../resources/images/vscode-eslint-not-defined.png"></div>
  284. <p>Above you can see I mis-spelled <code class="notranslate" translate="no">doTheThing</code> as <code class="notranslate" translate="no">doThing</code>. There's a red squiggle
  285. under <code class="notranslate" translate="no">doThing</code> and hovering over it it tells me it's undefined. One error
  286. avoided.</p>
  287. <p>If you're using <code class="notranslate" translate="no">&lt;script&gt;</code> tags to include three.js you'll get warnings using <code class="notranslate" translate="no">THREE</code> so add <code class="notranslate" translate="no">/* global THREE */</code> at the top of your
  288. JavaScript files to tell eslint that <code class="notranslate" translate="no">THREE</code> exists. (or better, use <code class="notranslate" translate="no">import</code> 😉)</p>
  289. <div class="threejs_center"><img style="width: 615px;" src="../resources/images/vscode-eslint-not-a-constructor.png"></div>
  290. <p>Above you can see eslint knows the rule that <code class="notranslate" translate="no">UpperCaseNames</code> are constructors
  291. and so you should be using <code class="notranslate" translate="no">new</code>. Another error caught and avoided. This is <a href="https://eslint.org/docs/rules/new-cap">the
  292. <code class="notranslate" translate="no">new-cap</code> rule</a>.</p>
  293. <p>There are <a href="https://eslint.org/docs/rules/">100s of rules you can turn on or off or
  294. customize</a>. For example above I mentioned you
  295. should use <code class="notranslate" translate="no">const</code> and <code class="notranslate" translate="no">let</code> over <code class="notranslate" translate="no">var</code>.</p>
  296. <p>Here I used <code class="notranslate" translate="no">var</code> and it warned me I should use <code class="notranslate" translate="no">let</code> or <code class="notranslate" translate="no">const</code></p>
  297. <div class="threejs_center"><img style="width: 615px;" src="../resources/images/vscode-eslint-var.png"></div>
  298. <p>Here I used <code class="notranslate" translate="no">let</code> but it saw I never change the value so it suggested I use <code class="notranslate" translate="no">const</code>.</p>
  299. <div class="threejs_center"><img style="width: 615px;" src="../resources/images/vscode-eslint-let.png"></div>
  300. <p>Of course if you'd prefer to keep using <code class="notranslate" translate="no">var</code> you can just turn off that rule.
  301. As I said above though I prefer to use <code class="notranslate" translate="no">const</code> and <code class="notranslate" translate="no">let</code> over <code class="notranslate" translate="no">var</code> as they just
  302. work better and prevent bugs.</p>
  303. <p>For those cases where you really need to override a rule <a href="https://eslint.org/docs/user-guide/configuring#disabling-rules-with-inline-comments">you can add comments
  304. to disable
  305. them</a>
  306. for a single line or a section of code.</p>
  307. <h1 id="if-you-really-need-to-support-legacy-browsers-use-a-transpiler">If you really need to support legacy browsers use a transpiler</h1>
  308. <p>Most modern browsers are auto-updated so using all these features will help you
  309. be productive and avoid bugs. That said, if you're on a project that absolutely
  310. must support old browsers there are <a href="https://babeljs.io">tools that will take your ES5/ES6/ES7 code
  311. and transpile the code back to pre ES5 Javascript</a>.</p>
  312. </div>
  313. </div>
  314. </div>
  315. <script src="../resources/prettify.js"></script>
  316. <script src="../resources/lesson.js"></script>
  317. </body></html>