threejs-lesson-utils.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. 'use strict';
  2. window.threejsLessonUtils = {
  3. init() {
  4. if (this.renderer) {
  5. return;
  6. }
  7. const canvas = document.querySelector('#c');
  8. const renderer = new THREE.WebGLRenderer({canvas: canvas, alpha: true});
  9. this.pixelRatio = Math.max(2, window.devicePixelRatio);
  10. this.renderer = renderer;
  11. this.renderFuncs = [];
  12. const resizeRendererToDisplaySize = (renderer) => {
  13. const canvas = renderer.domElement;
  14. const width = canvas.clientWidth * this.pixelRatio;
  15. const height = canvas.clientHeight * this.pixelRatio;
  16. const needResize = canvas.width !== width || canvas.height !== height;
  17. if (needResize) {
  18. renderer.setSize(width, height, false);
  19. }
  20. return needResize;
  21. };
  22. // Three r93 needs to render at least once for some reason.
  23. const scene = new THREE.Scene();
  24. const camera = new THREE.Camera();
  25. const render = (time) => {
  26. time *= 0.001;
  27. resizeRendererToDisplaySize(renderer);
  28. renderer.setScissorTest(false);
  29. // Three r93 needs to render at least once for some reason.
  30. renderer.render(scene, camera);
  31. renderer.setScissorTest(true);
  32. // maybe there is another way. Originally I used `position: fixed`
  33. // but the problem is if we can't render as fast as the browser
  34. // scrolls then our shapes lag. 1 or 2 frames of lag isn't too
  35. // horrible but iOS would often been 1/2 a second or worse.
  36. // By doing it this way the canvas will scroll which means the
  37. // worse that happens is part of the shapes scrolling on don't
  38. // get drawn for a few frames but the shapes that are on the screen
  39. // scroll perfectly.
  40. //
  41. // I'm using `transform` on the voodoo that it doesn't affect
  42. // layout as much as `top` since AFAIK setting `top` is in
  43. // the flow but `transform` is not though thinking about it
  44. // the given we're `position: absolute` maybe there's no difference?
  45. const transform = `translateY(${window.scrollY}px)`;
  46. renderer.domElement.style.transform = transform;
  47. this.renderFuncs.forEach((fn) => {
  48. fn(renderer, time);
  49. });
  50. requestAnimationFrame(render);
  51. };
  52. requestAnimationFrame(render);
  53. },
  54. addDiagrams(diagrams) {
  55. [...document.querySelectorAll('[data-diagram]')].forEach((elem) => {
  56. const name = elem.dataset.diagram;
  57. const info = diagrams[name];
  58. if (!info) {
  59. throw new Error(`no diagram: ${name}`);
  60. }
  61. this.addDiagram(elem, info);
  62. });
  63. },
  64. addDiagram(elem, info) {
  65. this.init();
  66. const scene = new THREE.Scene();
  67. let targetFOVDeg = 60;
  68. const aspect = 1;
  69. const zNear = 0.1;
  70. const zFar = 50;
  71. const camera = new THREE.PerspectiveCamera(targetFOVDeg, aspect, zNear, zFar);
  72. camera.position.z = 15;
  73. scene.add(camera);
  74. const obj3D = info.create({scene, camera});
  75. const promise = (obj3D instanceof Promise) ? obj3D : Promise.resolve(obj3D);
  76. const root = new THREE.Object3D();
  77. scene.add(root);
  78. const resizeFunctions = [];
  79. const updateFunctions = [];
  80. promise.then((result) => {
  81. const info = result instanceof THREE.Object3D ? {
  82. obj3D: result,
  83. } : result;
  84. const { obj3D, update, trackball, lights } = info;
  85. root.add(obj3D);
  86. targetFOVDeg = camera.fov;
  87. if (trackball !== false) {
  88. const controls = new THREE.TrackballControls(camera, elem);
  89. controls.noZoom = true;
  90. controls.noPan = true;
  91. resizeFunctions.push(controls.handleResize.bind(controls));
  92. updateFunctions.push(controls.update.bind(controls));
  93. }
  94. if (update) {
  95. updateFunctions.push(update);
  96. }
  97. // add the lights as children of the camera.
  98. // this is because TrackbacllControls move the camera.
  99. // We really want to rotate the object itself but there's no
  100. // controls for that so we fake it by putting all the lights
  101. // on the camera so they move with it.
  102. if (lights !== false) {
  103. camera.add(new THREE.HemisphereLight(0xaaaaaa, 0x444444, .5));
  104. const light = new THREE.DirectionalLight(0xffffff, 1);
  105. light.position.set(-1, 2, 4 - 15);
  106. camera.add(light);
  107. }
  108. });
  109. let oldWidth = -1;
  110. let oldHeight = -1;
  111. const render = (renderer, time) => {
  112. root.rotation.x = time * .1;
  113. root.rotation.y = time * .11;
  114. const rect = elem.getBoundingClientRect();
  115. if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  116. rect.right < 0 || rect.left > renderer.domElement.clientWidth) {
  117. return;
  118. }
  119. const width = (rect.right - rect.left) * this.pixelRatio;
  120. const height = (rect.bottom - rect.top) * this.pixelRatio;
  121. const left = rect.left * this.pixelRatio;
  122. const top = rect.top * this.pixelRatio;
  123. if (width !== oldWidth || height !== oldHeight) {
  124. oldWidth = width;
  125. oldHeight = height;
  126. resizeFunctions.forEach(fn => fn());
  127. }
  128. updateFunctions.forEach(fn => fn(time));
  129. const aspect = width / height;
  130. const fovDeg = aspect >= 1
  131. ? targetFOVDeg
  132. : THREE.Math.radToDeg(2 * Math.atan(Math.tan(THREE.Math.degToRad(targetFOVDeg) * .5) / aspect));
  133. camera.fov = fovDeg;
  134. camera.aspect = aspect;
  135. camera.updateProjectionMatrix();
  136. renderer.setViewport(left, top, width, height);
  137. renderer.setScissor(left, top, width, height);
  138. renderer.render(scene, camera);
  139. };
  140. this.renderFuncs.push(render);
  141. },
  142. };