threejs-lesson-utils.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. const fov = 60;
  68. const aspect = 1;
  69. const zNear = 0.1;
  70. const zFar = 50;
  71. const camera = new THREE.PerspectiveCamera(fov, 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 controls = new THREE.TrackballControls(camera, elem);
  79. controls.noZoom = true;
  80. controls.noPan = true;
  81. // add the lights as children of the camera.
  82. // this is because TrackbacllControls move the camera.
  83. // We really want to rotate the object itself but there's no
  84. // controls for that so we fake it by putting all the lights
  85. // on the camera so they move with it.
  86. camera.add(new THREE.HemisphereLight(0xaaaaaa, 0x444444, .5));
  87. const light = new THREE.DirectionalLight(0xffffff, 1);
  88. light.position.set(-1, 2, 4 - 15);
  89. camera.add(light);
  90. let updateFunction;
  91. promise.then((result) => {
  92. const info = result instanceof THREE.Object3D ? {
  93. obj3D: result,
  94. } : result;
  95. const { obj3D, update } = info;
  96. root.add(obj3D);
  97. updateFunction = update;
  98. });
  99. let oldWidth = -1;
  100. let oldHeight = -1;
  101. const render = (renderer, time) => {
  102. root.rotation.x = time * .1;
  103. root.rotation.y = time * .11;
  104. const rect = elem.getBoundingClientRect();
  105. if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  106. rect.right < 0 || rect.left > renderer.domElement.clientWidth) {
  107. return;
  108. }
  109. const width = (rect.right - rect.left) * this.pixelRatio;
  110. const height = (rect.bottom - rect.top) * this.pixelRatio;
  111. const left = rect.left * this.pixelRatio;
  112. const top = rect.top * this.pixelRatio;
  113. if (width !== oldWidth || height !== oldHeight) {
  114. oldWidth = width;
  115. oldHeight = height;
  116. controls.handleResize();
  117. }
  118. controls.update();
  119. if (updateFunction) {
  120. updateFunction(time);
  121. }
  122. const aspect = width / height;
  123. const targetFov = THREE.Math.degToRad(60);
  124. const fov = aspect >= 1
  125. ? targetFov
  126. : (2 * Math.atan(Math.tan(targetFov * .5) / aspect));
  127. camera.fov = THREE.Math.radToDeg(fov);
  128. camera.aspect = aspect;
  129. camera.updateProjectionMatrix();
  130. renderer.setViewport(left, top, width, height);
  131. renderer.setScissor(left, top, width, height);
  132. renderer.render(scene, camera);
  133. };
  134. this.renderFuncs.push(render);
  135. },
  136. };