offscreencanvas.html 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>OffscreenCanvas</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 – OffscreenCanvas">
  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>OffscreenCanvas</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas"><code class="notranslate" translate="no">OffscreenCanvas</code></a>
  29. is a relatively new browser feature currently only available in Chrome but apparently
  30. coming to other browsers. <code class="notranslate" translate="no">OffscreenCanvas</code> allows a web worker to render
  31. to a canvas. This is a way to offload heavy work, like rendering a complex 3D scene,
  32. to a web worker so as not to slow down the responsiveness of the browser. It
  33. also means data is loaded and parsed in the worker so possibly less jank while
  34. the page loads.</p>
  35. <p>Getting <em>started</em> using it is pretty straight forward. Let's port the 3 spinning cube
  36. example from <a href="responsive.html">the article on responsiveness</a>.</p>
  37. <p>Workers generally have their code separated
  38. into another script file whereas most of the examples on this site have had
  39. their scripts embedded into the HTML file of the page they are on.</p>
  40. <p>In our case we'll make a file called <code class="notranslate" translate="no">offscreencanvas-cubes.js</code> and
  41. copy all the JavaScript from <a href="responsive.html">the responsive example</a> into it. We'll then
  42. make the changes needed for it to run in a worker.</p>
  43. <p>We still need some JavaScript in our HTML file. The first thing
  44. we need to do there is look up the canvas and then transfer control of that
  45. canvas to be offscreen by calling <code class="notranslate" translate="no">canvas.transferControlToOffscreen</code>.</p>
  46. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function main() {
  47. const canvas = document.querySelector('#c');
  48. const offscreen = canvas.transferControlToOffscreen();
  49. ...
  50. </pre>
  51. <p>We can then start our worker with <code class="notranslate" translate="no">new Worker(pathToScript, {type: 'module'})</code>.
  52. and pass the <code class="notranslate" translate="no">offscreen</code> object to it.</p>
  53. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function main() {
  54. const canvas = document.querySelector('#c');
  55. const offscreen = canvas.transferControlToOffscreen();
  56. const worker = new Worker('offscreencanvas-cubes.js', {type: 'module'});
  57. worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
  58. }
  59. main();
  60. </pre>
  61. <p>It's important to note that workers can't access the <code class="notranslate" translate="no">DOM</code>. They
  62. can't look at HTML elements nor can they receive mouse events or
  63. keyboard events. The only thing they can generally do is respond
  64. to messages sent to them and send messages back to the page.</p>
  65. <p>To send a message to a worker we call <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage"><code class="notranslate" translate="no">worker.postMessage</code></a> and
  66. pass it 1 or 2 arguments. The first argument is a JavaScript object
  67. that will be <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">cloned</a>
  68. and sent to the worker. The second argument is an optional array
  69. of objects that are part of the first object that we want <em>transferred</em>
  70. to the worker. These objects will not be cloned. Instead they will be <em>transferred</em>
  71. and will cease to exist in the main page. Cease to exist is the probably
  72. the wrong description, rather they are neutered. Only certain types of
  73. objects can be transferred instead of cloned. They include <code class="notranslate" translate="no">OffscreenCanvas</code>
  74. so once transferred the <code class="notranslate" translate="no">offscreen</code> object back in the main page is useless.</p>
  75. <p>Workers receive messages from their <code class="notranslate" translate="no">onmessage</code> handler. The object
  76. we passed to <code class="notranslate" translate="no">postMessage</code> arrives on <code class="notranslate" translate="no">event.data</code> passed to the <code class="notranslate" translate="no">onmessage</code>
  77. handler on the worker. The code above declares a <code class="notranslate" translate="no">type: 'main'</code> in the object it passes
  78. to the worker. This object has no meaning to the browser. It's entirely for
  79. our own usage. We'll make a handler that based on <code class="notranslate" translate="no">type</code> calls
  80. a different function in the worker. Then we can add functions as
  81. needed and easily call them from the main page.</p>
  82. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const handlers = {
  83. main,
  84. };
  85. self.onmessage = function(e) {
  86. const fn = handlers[e.data.type];
  87. if (typeof fn !== 'function') {
  88. throw new Error('no handler for type: ' + e.data.type);
  89. }
  90. fn(e.data);
  91. };
  92. </pre>
  93. <p>You can see above we just look up the handler based on the <code class="notranslate" translate="no">type</code> pass it the <code class="notranslate" translate="no">data</code>
  94. that was sent from the main page.</p>
  95. <p>So now we just need to start changing the <code class="notranslate" translate="no">main</code> we pasted into
  96. <code class="notranslate" translate="no">offscreencanvas-cubes.js</code> from <a href="responsive.html">the responsive article</a>.</p>
  97. <p>Instead of looking up the canvas from the DOM we'll receive it from the
  98. event data.</p>
  99. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function main() {
  100. - const canvas = document.querySelector('#c');
  101. +function main(data) {
  102. + const {canvas} = data;
  103. const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
  104. ...
  105. </pre>
  106. <p>Remembering that workers can't see the DOM at all the first problem
  107. we run into is <code class="notranslate" translate="no">resizeRendererToDisplaySize</code> can't look at <code class="notranslate" translate="no">canvas.clientWidth</code>
  108. and <code class="notranslate" translate="no">canvas.clientHeight</code> as those are DOM values. Here's the original code</p>
  109. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function resizeRendererToDisplaySize(renderer) {
  110. const canvas = renderer.domElement;
  111. const width = canvas.clientWidth;
  112. const height = canvas.clientHeight;
  113. const needResize = canvas.width !== width || canvas.height !== height;
  114. if (needResize) {
  115. renderer.setSize(width, height, false);
  116. }
  117. return needResize;
  118. }
  119. </pre>
  120. <p>Instead we'll need to send sizes as they change to the worker.
  121. So, let's add some global state and keep the width and height there.</p>
  122. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const state = {
  123. width: 300, // canvas default
  124. height: 150, // canvas default
  125. };
  126. </pre>
  127. <p>Then let's add a <code class="notranslate" translate="no">'size'</code> handler to update those values. </p>
  128. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function size(data) {
  129. + state.width = data.width;
  130. + state.height = data.height;
  131. +}
  132. const handlers = {
  133. main,
  134. + size,
  135. };
  136. </pre>
  137. <p>Now we can change <code class="notranslate" translate="no">resizeRendererToDisplaySize</code> to use <code class="notranslate" translate="no">state.width</code> and <code class="notranslate" translate="no">state.height</code></p>
  138. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function resizeRendererToDisplaySize(renderer) {
  139. const canvas = renderer.domElement;
  140. - const width = canvas.clientWidth;
  141. - const height = canvas.clientHeight;
  142. + const width = state.width;
  143. + const height = state.height;
  144. const needResize = canvas.width !== width || canvas.height !== height;
  145. if (needResize) {
  146. renderer.setSize(width, height, false);
  147. }
  148. return needResize;
  149. }
  150. </pre>
  151. <p>and where we compute the aspect we need similar changes</p>
  152. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render(time) {
  153. time *= 0.001;
  154. if (resizeRendererToDisplaySize(renderer)) {
  155. - camera.aspect = canvas.clientWidth / canvas.clientHeight;
  156. + camera.aspect = state.width / state.height;
  157. camera.updateProjectionMatrix();
  158. }
  159. ...
  160. </pre>
  161. <p>Back in the main page we'll send a <code class="notranslate" translate="no">size</code> event anytime the page changes size.</p>
  162. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const worker = new Worker('offscreencanvas-picking.js', {type: 'module'});
  163. worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
  164. +function sendSize() {
  165. + worker.postMessage({
  166. + type: 'size',
  167. + width: canvas.clientWidth,
  168. + height: canvas.clientHeight,
  169. + });
  170. +}
  171. +
  172. +window.addEventListener('resize', sendSize);
  173. +sendSize();
  174. </pre>
  175. <p>We also call it once to send the initial size.</p>
  176. <p>And with just those few changes, assuming your browser fully supports <code class="notranslate" translate="no">OffscreenCanvas</code>
  177. it should work. Before we run it though let's check if the browser actually supports
  178. <code class="notranslate" translate="no">OffscreenCanvas</code> and if not display an error. First let's add some HTML to display the error.</p>
  179. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;body&gt;
  180. &lt;canvas id="c"&gt;&lt;/canvas&gt;
  181. + &lt;div id="noOffscreenCanvas" style="display:none;"&gt;
  182. + &lt;div&gt;no OffscreenCanvas support&lt;/div&gt;
  183. + &lt;/div&gt;
  184. &lt;/body&gt;
  185. </pre>
  186. <p>and some CSS for that</p>
  187. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">#noOffscreenCanvas {
  188. display: flex;
  189. width: 100%;
  190. height: 100%;
  191. align-items: center;
  192. justify-content: center;
  193. background: red;
  194. color: white;
  195. }
  196. </pre>
  197. <p>and then we can check for the existence of <code class="notranslate" translate="no">transferControlToOffscreen</code> to see
  198. if the browser supports <code class="notranslate" translate="no">OffscreenCanvas</code></p>
  199. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function main() {
  200. const canvas = document.querySelector('#c');
  201. + if (!canvas.transferControlToOffscreen) {
  202. + canvas.style.display = 'none';
  203. + document.querySelector('#noOffscreenCanvas').style.display = '';
  204. + return;
  205. + }
  206. const offscreen = canvas.transferControlToOffscreen();
  207. const worker = new Worker('offscreencanvas-picking.js', {type: 'module});
  208. worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
  209. ...
  210. </pre>
  211. <p>and with that, if your browser supports <code class="notranslate" translate="no">OffscreenCanvas</code> this example should work</p>
  212. <p></p><div translate="no" class="threejs_example_container notranslate">
  213. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/offscreencanvas.html"></iframe></div>
  214. <a class="threejs_center" href="/manual/examples/offscreencanvas.html" target="_blank">click here to open in a separate window</a>
  215. </div>
  216. <p></p>
  217. <p>So that's great but since not every browser supports <code class="notranslate" translate="no">OffscreenCanvas</code> at the moment
  218. let's change the code to work with both <code class="notranslate" translate="no">OffscreenCanvas</code> and if not then fallback to using
  219. the canvas in the main page like normal.</p>
  220. <blockquote>
  221. <p>As an aside, if you need OffscreenCanvas to make your page responsive then
  222. it's not clear what the point of having a fallback is. Maybe based on if
  223. you end up running on the main page or in a worker you might adjust the amount
  224. of work done so that when running in a worker you can do more than when
  225. running in the main page. What you do is really up to you.</p>
  226. </blockquote>
  227. <p>The first thing we should probably do is separate out the three.js
  228. code from the code that is specific to the worker. That way we can
  229. use the same code on both the main page and the worker. In other words
  230. we will now have 3 files</p>
  231. <ol>
  232. <li><p>our html file.</p>
  233. <p><code class="notranslate" translate="no">threejs-offscreencanvas-w-fallback.html</code></p>
  234. </li>
  235. <li><p>a JavaScript that contains our three.js code.</p>
  236. <p><code class="notranslate" translate="no">shared-cubes.js</code></p>
  237. </li>
  238. <li><p>our worker support code</p>
  239. <p><code class="notranslate" translate="no">offscreencanvas-worker-cubes.js</code></p>
  240. </li>
  241. </ol>
  242. <p><code class="notranslate" translate="no">shared-cubes.js</code> and <code class="notranslate" translate="no">offscreencanvas-worker-cubes.js</code> are basically
  243. the split of our previous <code class="notranslate" translate="no">offscreencanvas-cubes.js</code> file. First we
  244. copy all of <code class="notranslate" translate="no">offscreencanvas-cubes.js</code> to <code class="notranslate" translate="no">shared-cube.js</code>. Then
  245. we rename <code class="notranslate" translate="no">main</code> to <code class="notranslate" translate="no">init</code> since we already have a <code class="notranslate" translate="no">main</code> in our
  246. HTML file and we need to export <code class="notranslate" translate="no">init</code> and <code class="notranslate" translate="no">state</code></p>
  247. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from 'three';
  248. -const state = {
  249. +export const state = {
  250. width: 300, // canvas default
  251. height: 150, // canvas default
  252. };
  253. -function main(data) {
  254. +export function init(data) {
  255. const {canvas} = data;
  256. const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
  257. </pre>
  258. <p>and cut out the just the non three.js relates parts</p>
  259. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function size(data) {
  260. - state.width = data.width;
  261. - state.height = data.height;
  262. -}
  263. -
  264. -const handlers = {
  265. - main,
  266. - size,
  267. -};
  268. -
  269. -self.onmessage = function(e) {
  270. - const fn = handlers[e.data.type];
  271. - if (typeof fn !== 'function') {
  272. - throw new Error('no handler for type: ' + e.data.type);
  273. - }
  274. - fn(e.data);
  275. -};
  276. </pre>
  277. <p>Then we copy those parts we just deleted to <code class="notranslate" translate="no">offscreencanvas-worker-cubes.js</code>
  278. and import <code class="notranslate" translate="no">shared-cubes.js</code> as well as call <code class="notranslate" translate="no">init</code> instead of <code class="notranslate" translate="no">main</code>.</p>
  279. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import {init, state} from './shared-cubes.js';
  280. function size(data) {
  281. state.width = data.width;
  282. state.height = data.height;
  283. }
  284. const handlers = {
  285. - main,
  286. + init,
  287. size,
  288. };
  289. self.onmessage = function(e) {
  290. const fn = handlers[e.data.type];
  291. if (typeof fn !== 'function') {
  292. throw new Error('no handler for type: ' + e.data.type);
  293. }
  294. fn(e.data);
  295. };
  296. </pre>
  297. <p>Similarly we need to include <code class="notranslate" translate="no">shared-cubes.js</code> in the main page</p>
  298. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;script type="module"&gt;
  299. +import {init, state} from './shared-cubes.js';
  300. </pre>
  301. <p>We can remove the HTML and CSS we added previously</p>
  302. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;body&gt;
  303. &lt;canvas id="c"&gt;&lt;/canvas&gt;
  304. - &lt;div id="noOffscreenCanvas" style="display:none;"&gt;
  305. - &lt;div&gt;no OffscreenCanvas support&lt;/div&gt;
  306. - &lt;/div&gt;
  307. &lt;/body&gt;
  308. </pre>
  309. <p>and some CSS for that</p>
  310. <pre class="prettyprint showlinemods notranslate lang-css" translate="no">-#noOffscreenCanvas {
  311. - display: flex;
  312. - width: 100%;
  313. - height: 100%;
  314. - align-items: center;
  315. - justify-content: center;
  316. - background: red;
  317. - color: white;
  318. -}
  319. </pre>
  320. <p>Then let's change the code in the main page to call one start
  321. function or another depending on if the browser supports <code class="notranslate" translate="no">OffscreenCanvas</code>.</p>
  322. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function main() {
  323. const canvas = document.querySelector('#c');
  324. - if (!canvas.transferControlToOffscreen) {
  325. - canvas.style.display = 'none';
  326. - document.querySelector('#noOffscreenCanvas').style.display = '';
  327. - return;
  328. - }
  329. - const offscreen = canvas.transferControlToOffscreen();
  330. - const worker = new Worker('offscreencanvas-picking.js', {type: 'module'});
  331. - worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
  332. + if (canvas.transferControlToOffscreen) {
  333. + startWorker(canvas);
  334. + } else {
  335. + startMainPage(canvas);
  336. + }
  337. ...
  338. </pre>
  339. <p>We'll move all the code we had to setup the worker inside <code class="notranslate" translate="no">startWorker</code></p>
  340. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function startWorker(canvas) {
  341. const offscreen = canvas.transferControlToOffscreen();
  342. const worker = new Worker('offscreencanvas-worker-cubes.js', {type: 'module'});
  343. worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
  344. function sendSize() {
  345. worker.postMessage({
  346. type: 'size',
  347. width: canvas.clientWidth,
  348. height: canvas.clientHeight,
  349. });
  350. }
  351. window.addEventListener('resize', sendSize);
  352. sendSize();
  353. console.log('using OffscreenCanvas');
  354. }
  355. </pre>
  356. <p>and send <code class="notranslate" translate="no">init</code> instead of <code class="notranslate" translate="no">main</code></p>
  357. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">- worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
  358. + worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
  359. </pre>
  360. <p>for starting in the main page we can do this</p>
  361. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function startMainPage(canvas) {
  362. init({canvas});
  363. function sendSize() {
  364. state.width = canvas.clientWidth;
  365. state.height = canvas.clientHeight;
  366. }
  367. window.addEventListener('resize', sendSize);
  368. sendSize();
  369. console.log('using regular canvas');
  370. }
  371. </pre>
  372. <p>and with that our example will run either in an OffscreenCanvas or
  373. fallback to running in the main page.</p>
  374. <p></p><div translate="no" class="threejs_example_container notranslate">
  375. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/offscreencanvas-w-fallback.html"></iframe></div>
  376. <a class="threejs_center" href="/manual/examples/offscreencanvas-w-fallback.html" target="_blank">click here to open in a separate window</a>
  377. </div>
  378. <p></p>
  379. <p>So that was relatively easy. Let's try picking. We'll take some code from
  380. the <code class="notranslate" translate="no">RayCaster</code> example from <a href="picking.html">the article on picking</a>
  381. and make it work offscreen.</p>
  382. <p>Let's copy the <code class="notranslate" translate="no">shared-cube.js</code> to <code class="notranslate" translate="no">shared-picking.js</code> and add the
  383. picking parts. We copy in the <code class="notranslate" translate="no">PickHelper</code> </p>
  384. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class PickHelper {
  385. constructor() {
  386. this.raycaster = new THREE.Raycaster();
  387. this.pickedObject = null;
  388. this.pickedObjectSavedColor = 0;
  389. }
  390. pick(normalizedPosition, scene, camera, time) {
  391. // restore the color if there is a picked object
  392. if (this.pickedObject) {
  393. this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
  394. this.pickedObject = undefined;
  395. }
  396. // cast a ray through the frustum
  397. this.raycaster.setFromCamera(normalizedPosition, camera);
  398. // get the list of objects the ray intersected
  399. const intersectedObjects = this.raycaster.intersectObjects(scene.children);
  400. if (intersectedObjects.length) {
  401. // pick the first object. It's the closest one
  402. this.pickedObject = intersectedObjects[0].object;
  403. // save its color
  404. this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
  405. // set its emissive color to flashing red/yellow
  406. this.pickedObject.material.emissive.setHex((time * 8) % 2 &gt; 1 ? 0xFFFF00 : 0xFF0000);
  407. }
  408. }
  409. }
  410. const pickPosition = {x: 0, y: 0};
  411. const pickHelper = new PickHelper();
  412. </pre>
  413. <p>We updated <code class="notranslate" translate="no">pickPosition</code> from the mouse like this</p>
  414. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function getCanvasRelativePosition(event) {
  415. const rect = canvas.getBoundingClientRect();
  416. return {
  417. x: (event.clientX - rect.left) * canvas.width / rect.width,
  418. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  419. };
  420. }
  421. function setPickPosition(event) {
  422. const pos = getCanvasRelativePosition(event);
  423. pickPosition.x = (pos.x / canvas.width ) * 2 - 1;
  424. pickPosition.y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
  425. }
  426. window.addEventListener('mousemove', setPickPosition);
  427. </pre>
  428. <p>A worker can't read the mouse position directly so just like the size code
  429. let's send a message with the mouse position. Like the size code we'll
  430. send the mouse position and update <code class="notranslate" translate="no">pickPosition</code></p>
  431. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function size(data) {
  432. state.width = data.width;
  433. state.height = data.height;
  434. }
  435. +function mouse(data) {
  436. + pickPosition.x = data.x;
  437. + pickPosition.y = data.y;
  438. +}
  439. const handlers = {
  440. init,
  441. + mouse,
  442. size,
  443. };
  444. self.onmessage = function(e) {
  445. const fn = handlers[e.data.type];
  446. if (typeof fn !== 'function') {
  447. throw new Error('no handler for type: ' + e.data.type);
  448. }
  449. fn(e.data);
  450. };
  451. </pre>
  452. <p>Back in our main page we need to add code to pass the mouse
  453. to the worker or the main page.</p>
  454. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+let sendMouse;
  455. function startWorker(canvas) {
  456. const offscreen = canvas.transferControlToOffscreen();
  457. const worker = new Worker('offscreencanvas-worker-picking.js', {type: 'module'});
  458. worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
  459. + sendMouse = (x, y) =&gt; {
  460. + worker.postMessage({
  461. + type: 'mouse',
  462. + x,
  463. + y,
  464. + });
  465. + };
  466. function sendSize() {
  467. worker.postMessage({
  468. type: 'size',
  469. width: canvas.clientWidth,
  470. height: canvas.clientHeight,
  471. });
  472. }
  473. window.addEventListener('resize', sendSize);
  474. sendSize();
  475. console.log('using OffscreenCanvas'); /* eslint-disable-line no-console */
  476. }
  477. function startMainPage(canvas) {
  478. init({canvas});
  479. + sendMouse = (x, y) =&gt; {
  480. + pickPosition.x = x;
  481. + pickPosition.y = y;
  482. + };
  483. function sendSize() {
  484. state.width = canvas.clientWidth;
  485. state.height = canvas.clientHeight;
  486. }
  487. window.addEventListener('resize', sendSize);
  488. sendSize();
  489. console.log('using regular canvas'); /* eslint-disable-line no-console */
  490. }
  491. </pre>
  492. <p>Then we can copy in all the mouse handling code to the main page and
  493. make just minor changes to use <code class="notranslate" translate="no">sendMouse</code></p>
  494. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function setPickPosition(event) {
  495. const pos = getCanvasRelativePosition(event);
  496. - pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
  497. - pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
  498. + sendMouse(
  499. + (pos.x / canvas.clientWidth ) * 2 - 1,
  500. + (pos.y / canvas.clientHeight) * -2 + 1); // note we flip Y
  501. }
  502. function clearPickPosition() {
  503. // unlike the mouse which always has a position
  504. // if the user stops touching the screen we want
  505. // to stop picking. For now we just pick a value
  506. // unlikely to pick something
  507. - pickPosition.x = -100000;
  508. - pickPosition.y = -100000;
  509. + sendMouse(-100000, -100000);
  510. }
  511. window.addEventListener('mousemove', setPickPosition);
  512. window.addEventListener('mouseout', clearPickPosition);
  513. window.addEventListener('mouseleave', clearPickPosition);
  514. window.addEventListener('touchstart', (event) =&gt; {
  515. // prevent the window from scrolling
  516. event.preventDefault();
  517. setPickPosition(event.touches[0]);
  518. }, {passive: false});
  519. window.addEventListener('touchmove', (event) =&gt; {
  520. setPickPosition(event.touches[0]);
  521. });
  522. window.addEventListener('touchend', clearPickPosition);
  523. </pre>
  524. <p>and with that picking should be working with <code class="notranslate" translate="no">OffscreenCanvas</code>.</p>
  525. <p></p><div translate="no" class="threejs_example_container notranslate">
  526. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/offscreencanvas-w-picking.html"></iframe></div>
  527. <a class="threejs_center" href="/manual/examples/offscreencanvas-w-picking.html" target="_blank">click here to open in a separate window</a>
  528. </div>
  529. <p></p>
  530. <p>Let's take it one more step and add in the <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a>.
  531. This will be little more involved. The <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> use
  532. the DOM pretty extensively checking the mouse, touch events,
  533. and the keyboard.</p>
  534. <p>Unlike our code so far we can't really use a global <code class="notranslate" translate="no">state</code> object
  535. without re-writing all the OrbitControls code to work with it.
  536. The OrbitControls take an <code class="notranslate" translate="no">HTMLElement</code> to which they attach most
  537. of the DOM events they use. Maybe we could pass in our own
  538. object that has the same API surface as a DOM element.
  539. We only need to support the features the OrbitControls need.</p>
  540. <p>Digging through the <a href="https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/OrbitControls.js">OrbitControls source code</a>
  541. it looks like we need to handle the following events.</p>
  542. <ul>
  543. <li>contextmenu</li>
  544. <li>pointerdown</li>
  545. <li>pointermove</li>
  546. <li>pointerup</li>
  547. <li>touchstart</li>
  548. <li>touchmove</li>
  549. <li>touchend</li>
  550. <li>wheel</li>
  551. <li>keydown</li>
  552. </ul>
  553. <p>For the pointer events we need the <code class="notranslate" translate="no">ctrlKey</code>, <code class="notranslate" translate="no">metaKey</code>, <code class="notranslate" translate="no">shiftKey</code>,
  554. <code class="notranslate" translate="no">button</code>, <code class="notranslate" translate="no">pointerType</code>, <code class="notranslate" translate="no">clientX</code>, <code class="notranslate" translate="no">clientY</code>, <code class="notranslate" translate="no">pageX</code>, and <code class="notranslate" translate="no">pageY</code>, properties.</p>
  555. <p>For the keydown events we need the <code class="notranslate" translate="no">ctrlKey</code>, <code class="notranslate" translate="no">metaKey</code>, <code class="notranslate" translate="no">shiftKey</code>,
  556. and <code class="notranslate" translate="no">keyCode</code> properties.</p>
  557. <p>For the wheel event we only need the <code class="notranslate" translate="no">deltaY</code> property.</p>
  558. <p>And for the touch events we only need <code class="notranslate" translate="no">pageX</code> and <code class="notranslate" translate="no">pageY</code> from
  559. the <code class="notranslate" translate="no">touches</code> property.</p>
  560. <p>So, let's make a proxy object pair. One part will run in the main page,
  561. get all those events, and pass on the relevant property values
  562. to the worker. The other part will run in the worker, receive those
  563. events and pass them on using events that have the same structure
  564. as the original DOM events so the OrbitControls won't be able to
  565. tell the difference.</p>
  566. <p>Here's the code for the worker part.</p>
  567. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import {EventDispatcher} from 'three';
  568. class ElementProxyReceiver extends EventDispatcher {
  569. constructor() {
  570. super();
  571. }
  572. handleEvent(data) {
  573. this.dispatchEvent(data);
  574. }
  575. }
  576. </pre>
  577. <p>All it does is if it receives a message it dispatches it.
  578. It inherits from <a href="/docs/#api/en/core/EventDispatcher"><code class="notranslate" translate="no">EventDispatcher</code></a> which provides methods like
  579. <code class="notranslate" translate="no">addEventListener</code> and <code class="notranslate" translate="no">removeEventListener</code> just like a DOM
  580. element so if we pass it to the OrbitControls it should work.</p>
  581. <p><code class="notranslate" translate="no">ElementProxyReceiver</code> handles 1 element. In our case we only need
  582. one but it's best to think head so lets make a manager to manage
  583. more than one of them.</p>
  584. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ProxyManager {
  585. constructor() {
  586. this.targets = {};
  587. this.handleEvent = this.handleEvent.bind(this);
  588. }
  589. makeProxy(data) {
  590. const {id} = data;
  591. const proxy = new ElementProxyReceiver();
  592. this.targets[id] = proxy;
  593. }
  594. getProxy(id) {
  595. return this.targets[id];
  596. }
  597. handleEvent(data) {
  598. this.targets[data.id].handleEvent(data.data);
  599. }
  600. }
  601. </pre>
  602. <p>We can make a instance of <code class="notranslate" translate="no">ProxyManager</code> and call its <code class="notranslate" translate="no">makeProxy</code>
  603. method with an id which will make an <code class="notranslate" translate="no">ElementProxyReceiver</code> that
  604. responds to messages with that id.</p>
  605. <p>Let's hook it up to our worker's message handler.</p>
  606. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const proxyManager = new ProxyManager();
  607. function start(data) {
  608. const proxy = proxyManager.getProxy(data.canvasId);
  609. init({
  610. canvas: data.canvas,
  611. inputElement: proxy,
  612. });
  613. }
  614. function makeProxy(data) {
  615. proxyManager.makeProxy(data);
  616. }
  617. ...
  618. const handlers = {
  619. - init,
  620. - mouse,
  621. + start,
  622. + makeProxy,
  623. + event: proxyManager.handleEvent,
  624. size,
  625. };
  626. self.onmessage = function(e) {
  627. const fn = handlers[e.data.type];
  628. if (typeof fn !== 'function') {
  629. throw new Error('no handler for type: ' + e.data.type);
  630. }
  631. fn(e.data);
  632. };
  633. </pre>
  634. <p>In our shared three.js code we need to import the <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> and set them up.</p>
  635. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from 'three';
  636. +import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
  637. export function init(data) {
  638. - const {canvas} = data;
  639. + const {canvas, inputElement} = data;
  640. const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
  641. + const controls = new OrbitControls(camera, inputElement);
  642. + controls.target.set(0, 0, 0);
  643. + controls.update();
  644. </pre>
  645. <p>Notice we're passing the OrbitControls our proxy via <code class="notranslate" translate="no">inputElement</code>
  646. instead of passing in the canvas like we do in other non-OffscreenCanvas
  647. examples.</p>
  648. <p>Next we can move all the picking event code from the HTML file
  649. to the shared three.js code as well while changing
  650. <code class="notranslate" translate="no">canvas</code> to <code class="notranslate" translate="no">inputElement</code>.</p>
  651. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function getCanvasRelativePosition(event) {
  652. - const rect = canvas.getBoundingClientRect();
  653. + const rect = inputElement.getBoundingClientRect();
  654. return {
  655. x: event.clientX - rect.left,
  656. y: event.clientY - rect.top,
  657. };
  658. }
  659. function setPickPosition(event) {
  660. const pos = getCanvasRelativePosition(event);
  661. - sendMouse(
  662. - (pos.x / canvas.clientWidth ) * 2 - 1,
  663. - (pos.y / canvas.clientHeight) * -2 + 1); // note we flip Y
  664. + pickPosition.x = (pos.x / inputElement.clientWidth ) * 2 - 1;
  665. + pickPosition.y = (pos.y / inputElement.clientHeight) * -2 + 1; // note we flip Y
  666. }
  667. function clearPickPosition() {
  668. // unlike the mouse which always has a position
  669. // if the user stops touching the screen we want
  670. // to stop picking. For now we just pick a value
  671. // unlikely to pick something
  672. - sendMouse(-100000, -100000);
  673. + pickPosition.x = -100000;
  674. + pickPosition.y = -100000;
  675. }
  676. *inputElement.addEventListener('mousemove', setPickPosition);
  677. *inputElement.addEventListener('mouseout', clearPickPosition);
  678. *inputElement.addEventListener('mouseleave', clearPickPosition);
  679. *inputElement.addEventListener('touchstart', (event) =&gt; {
  680. // prevent the window from scrolling
  681. event.preventDefault();
  682. setPickPosition(event.touches[0]);
  683. }, {passive: false});
  684. *inputElement.addEventListener('touchmove', (event) =&gt; {
  685. setPickPosition(event.touches[0]);
  686. });
  687. *inputElement.addEventListener('touchend', clearPickPosition);
  688. </pre>
  689. <p>Back in the main page we need code to send messages for
  690. all the events we enumerated above.</p>
  691. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">let nextProxyId = 0;
  692. class ElementProxy {
  693. constructor(element, worker, eventHandlers) {
  694. this.id = nextProxyId++;
  695. this.worker = worker;
  696. const sendEvent = (data) =&gt; {
  697. this.worker.postMessage({
  698. type: 'event',
  699. id: this.id,
  700. data,
  701. });
  702. };
  703. // register an id
  704. worker.postMessage({
  705. type: 'makeProxy',
  706. id: this.id,
  707. });
  708. for (const [eventName, handler] of Object.entries(eventHandlers)) {
  709. element.addEventListener(eventName, function(event) {
  710. handler(event, sendEvent);
  711. });
  712. }
  713. }
  714. }
  715. </pre>
  716. <p><code class="notranslate" translate="no">ElementProxy</code> takes the element who's events we want to proxy. It
  717. then registers an id with the worker by picking one and sending it
  718. via the <code class="notranslate" translate="no">makeProxy</code> message we setup earlier. The worker will make
  719. an <code class="notranslate" translate="no">ElementProxyReceiver</code> and register it to that id.</p>
  720. <p>We then have an object of event handlers to register. This way
  721. we can pass handlers only for these events we want to forward to
  722. the worker.</p>
  723. <p>When we start the worker we first make a proxy and pass in our event handlers.</p>
  724. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function startWorker(canvas) {
  725. const offscreen = canvas.transferControlToOffscreen();
  726. const worker = new Worker('offscreencanvas-worker-orbitcontrols.js', {type: 'module'});
  727. + const eventHandlers = {
  728. + contextmenu: preventDefaultHandler,
  729. + mousedown: mouseEventHandler,
  730. + mousemove: mouseEventHandler,
  731. + mouseup: mouseEventHandler,
  732. + pointerdown: mouseEventHandler,
  733. + pointermove: mouseEventHandler,
  734. + pointerup: mouseEventHandler,
  735. + touchstart: touchEventHandler,
  736. + touchmove: touchEventHandler,
  737. + touchend: touchEventHandler,
  738. + wheel: wheelEventHandler,
  739. + keydown: filteredKeydownEventHandler,
  740. + };
  741. + const proxy = new ElementProxy(canvas, worker, eventHandlers);
  742. worker.postMessage({
  743. type: 'start',
  744. canvas: offscreen,
  745. + canvasId: proxy.id,
  746. }, [offscreen]);
  747. console.log('using OffscreenCanvas'); /* eslint-disable-line no-console */
  748. }
  749. </pre>
  750. <p>And here are the event handlers. All they do is copy a list of properties
  751. from the event they receive. They are passed a <code class="notranslate" translate="no">sendEvent</code> function to which they pass the data
  752. they make. That function will add the correct id and send it to the worker.</p>
  753. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mouseEventHandler = makeSendPropertiesHandler([
  754. 'ctrlKey',
  755. 'metaKey',
  756. 'shiftKey',
  757. 'button',
  758. 'pointerType',
  759. 'clientX',
  760. 'clientY',
  761. 'pageX',
  762. 'pageY',
  763. ]);
  764. const wheelEventHandlerImpl = makeSendPropertiesHandler([
  765. 'deltaX',
  766. 'deltaY',
  767. ]);
  768. const keydownEventHandler = makeSendPropertiesHandler([
  769. 'ctrlKey',
  770. 'metaKey',
  771. 'shiftKey',
  772. 'keyCode',
  773. ]);
  774. function wheelEventHandler(event, sendFn) {
  775. event.preventDefault();
  776. wheelEventHandlerImpl(event, sendFn);
  777. }
  778. function preventDefaultHandler(event) {
  779. event.preventDefault();
  780. }
  781. function copyProperties(src, properties, dst) {
  782. for (const name of properties) {
  783. dst[name] = src[name];
  784. }
  785. }
  786. function makeSendPropertiesHandler(properties) {
  787. return function sendProperties(event, sendFn) {
  788. const data = {type: event.type};
  789. copyProperties(event, properties, data);
  790. sendFn(data);
  791. };
  792. }
  793. function touchEventHandler(event, sendFn) {
  794. const touches = [];
  795. const data = {type: event.type, touches};
  796. for (let i = 0; i &lt; event.touches.length; ++i) {
  797. const touch = event.touches[i];
  798. touches.push({
  799. pageX: touch.pageX,
  800. pageY: touch.pageY,
  801. });
  802. }
  803. sendFn(data);
  804. }
  805. // The four arrow keys
  806. const orbitKeys = {
  807. '37': true, // left
  808. '38': true, // up
  809. '39': true, // right
  810. '40': true, // down
  811. };
  812. function filteredKeydownEventHandler(event, sendFn) {
  813. const {keyCode} = event;
  814. if (orbitKeys[keyCode]) {
  815. event.preventDefault();
  816. keydownEventHandler(event, sendFn);
  817. }
  818. }
  819. </pre>
  820. <p>This seems close to running but if we actually try it we'll see
  821. that the <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> need a few more things.</p>
  822. <p>One is they call <code class="notranslate" translate="no">element.focus</code>. We don't need that to happen
  823. in the worker so let's just add a stub.</p>
  824. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ElementProxyReceiver extends THREE.EventDispatcher {
  825. constructor() {
  826. super();
  827. }
  828. handleEvent(data) {
  829. this.dispatchEvent(data);
  830. }
  831. + focus() {
  832. + // no-op
  833. + }
  834. }
  835. </pre>
  836. <p>Another is they call <code class="notranslate" translate="no">event.preventDefault</code> and <code class="notranslate" translate="no">event.stopPropagation</code>.
  837. We're already handling that in the main page so those can also be a noop.</p>
  838. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function noop() {
  839. +}
  840. class ElementProxyReceiver extends THREE.EventDispatcher {
  841. constructor() {
  842. super();
  843. }
  844. handleEvent(data) {
  845. + data.preventDefault = noop;
  846. + data.stopPropagation = noop;
  847. this.dispatchEvent(data);
  848. }
  849. focus() {
  850. // no-op
  851. }
  852. }
  853. </pre>
  854. <p>Another is they look at <code class="notranslate" translate="no">clientWidth</code> and <code class="notranslate" translate="no">clientHeight</code>. We
  855. were passing the size before but we can update the proxy pair
  856. to pass that as well.</p>
  857. <p>In the worker...</p>
  858. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ElementProxyReceiver extends THREE.EventDispatcher {
  859. constructor() {
  860. super();
  861. }
  862. + get clientWidth() {
  863. + return this.width;
  864. + }
  865. + get clientHeight() {
  866. + return this.height;
  867. + }
  868. + getBoundingClientRect() {
  869. + return {
  870. + left: this.left,
  871. + top: this.top,
  872. + width: this.width,
  873. + height: this.height,
  874. + right: this.left + this.width,
  875. + bottom: this.top + this.height,
  876. + };
  877. + }
  878. handleEvent(data) {
  879. + if (data.type === 'size') {
  880. + this.left = data.left;
  881. + this.top = data.top;
  882. + this.width = data.width;
  883. + this.height = data.height;
  884. + return;
  885. + }
  886. data.preventDefault = noop;
  887. data.stopPropagation = noop;
  888. this.dispatchEvent(data);
  889. }
  890. focus() {
  891. // no-op
  892. }
  893. }
  894. </pre>
  895. <p>back in the main page we need to send the size and the left and top positions as well.
  896. Note that as is we don't handle if the canvas moves, only if it resizes. If you wanted
  897. to handle moving you'd need to call <code class="notranslate" translate="no">sendSize</code> anytime something moved the canvas.</p>
  898. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ElementProxy {
  899. constructor(element, worker, eventHandlers) {
  900. this.id = nextProxyId++;
  901. this.worker = worker;
  902. const sendEvent = (data) =&gt; {
  903. this.worker.postMessage({
  904. type: 'event',
  905. id: this.id,
  906. data,
  907. });
  908. };
  909. // register an id
  910. worker.postMessage({
  911. type: 'makeProxy',
  912. id: this.id,
  913. });
  914. + sendSize();
  915. for (const [eventName, handler] of Object.entries(eventHandlers)) {
  916. element.addEventListener(eventName, function(event) {
  917. handler(event, sendEvent);
  918. });
  919. }
  920. + function sendSize() {
  921. + const rect = element.getBoundingClientRect();
  922. + sendEvent({
  923. + type: 'size',
  924. + left: rect.left,
  925. + top: rect.top,
  926. + width: element.clientWidth,
  927. + height: element.clientHeight,
  928. + });
  929. + }
  930. +
  931. + window.addEventListener('resize', sendSize);
  932. }
  933. }
  934. </pre>
  935. <p>and in our shared three.js code we no longer need <code class="notranslate" translate="no">state</code></p>
  936. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-export const state = {
  937. - width: 300, // canvas default
  938. - height: 150, // canvas default
  939. -};
  940. ...
  941. function resizeRendererToDisplaySize(renderer) {
  942. const canvas = renderer.domElement;
  943. - const width = state.width;
  944. - const height = state.height;
  945. + const width = inputElement.clientWidth;
  946. + const height = inputElement.clientHeight;
  947. const needResize = canvas.width !== width || canvas.height !== height;
  948. if (needResize) {
  949. renderer.setSize(width, height, false);
  950. }
  951. return needResize;
  952. }
  953. function render(time) {
  954. time *= 0.001;
  955. if (resizeRendererToDisplaySize(renderer)) {
  956. - camera.aspect = state.width / state.height;
  957. + camera.aspect = inputElement.clientWidth / inputElement.clientHeight;
  958. camera.updateProjectionMatrix();
  959. }
  960. ...
  961. </pre>
  962. <p>A few more hacks. The OrbitControls add <code class="notranslate" translate="no">pointermove</code> and <code class="notranslate" translate="no">pointerup</code> events to the
  963. <code class="notranslate" translate="no">ownerDocument</code> of the element to handle mouse capture (when the mouse goes
  964. outside the window).</p>
  965. <p>Further the code references the global <code class="notranslate" translate="no">document</code> but there is no global document
  966. in a worker. </p>
  967. <p>We can solve all of these with a 2 quick hacks. In our worker
  968. code we'll re-use our proxy for both problems.</p>
  969. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function start(data) {
  970. const proxy = proxyManager.getProxy(data.canvasId);
  971. + proxy.ownerDocument = proxy; // HACK!
  972. + self.document = {} // HACK!
  973. init({
  974. canvas: data.canvas,
  975. inputElement: proxy,
  976. });
  977. }
  978. </pre>
  979. <p>This will give the <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> something to inspect which
  980. matches their expectations.</p>
  981. <p>I know that was kind of hard to follow. The short version is:
  982. <code class="notranslate" translate="no">ElementProxy</code> runs on the main page and forwards DOM events
  983. to <code class="notranslate" translate="no">ElementProxyReceiver</code> in the worker which
  984. masquerades as an <code class="notranslate" translate="no">HTMLElement</code> that we can use both with the
  985. <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> and with our own code.</p>
  986. <p>The final thing is our fallback when we are not using OffscreenCanvas.
  987. All we have to do is pass the canvas itself as our <code class="notranslate" translate="no">inputElement</code>.</p>
  988. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function startMainPage(canvas) {
  989. - init({canvas});
  990. + init({canvas, inputElement: canvas});
  991. console.log('using regular canvas');
  992. }
  993. </pre>
  994. <p>and now we should have OrbitControls working with OffscreenCanvas</p>
  995. <p></p><div translate="no" class="threejs_example_container notranslate">
  996. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/offscreencanvas-w-orbitcontrols.html"></iframe></div>
  997. <a class="threejs_center" href="/manual/examples/offscreencanvas-w-orbitcontrols.html" target="_blank">click here to open in a separate window</a>
  998. </div>
  999. <p></p>
  1000. <p>This is probably the most complicated example on this site. It's a
  1001. little hard to follow because there are 3 files involved for each
  1002. sample. The HTML file, the worker file, the shared three.js code.</p>
  1003. <p>I hope it wasn't too difficult to understand and that it provided some
  1004. useful examples of working with three.js, OffscreenCanvas and web workers.</p>
  1005. </div>
  1006. </div>
  1007. </div>
  1008. <script src="../resources/prettify.js"></script>
  1009. <script src="../resources/lesson.js"></script>
  1010. </body></html>