offscreencanvas-cubes.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. 'use strict'; // eslint-disable-line
  2. /* global importScripts, THREE */
  3. importScripts('resources/threejs/r115/build/three.min.js');
  4. const state = {
  5. width: 300, // canvas default
  6. height: 150, // canvas default
  7. };
  8. function main(data) {
  9. const {canvas} = data;
  10. const renderer = new THREE.WebGLRenderer({canvas});
  11. state.width = canvas.width;
  12. state.height = canvas.height;
  13. const fov = 75;
  14. const aspect = 2; // the canvas default
  15. const near = 0.1;
  16. const far = 100;
  17. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  18. camera.position.z = 4;
  19. const scene = new THREE.Scene();
  20. {
  21. const color = 0xFFFFFF;
  22. const intensity = 1;
  23. const light = new THREE.DirectionalLight(color, intensity);
  24. light.position.set(-1, 2, 4);
  25. scene.add(light);
  26. }
  27. const boxWidth = 1;
  28. const boxHeight = 1;
  29. const boxDepth = 1;
  30. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  31. function makeInstance(geometry, color, x) {
  32. const material = new THREE.MeshPhongMaterial({
  33. color,
  34. });
  35. const cube = new THREE.Mesh(geometry, material);
  36. scene.add(cube);
  37. cube.position.x = x;
  38. return cube;
  39. }
  40. const cubes = [
  41. makeInstance(geometry, 0x44aa88, 0),
  42. makeInstance(geometry, 0x8844aa, -2),
  43. makeInstance(geometry, 0xaa8844, 2),
  44. ];
  45. function resizeRendererToDisplaySize(renderer) {
  46. const canvas = renderer.domElement;
  47. const width = state.width;
  48. const height = state.height;
  49. const needResize = canvas.width !== width || canvas.height !== height;
  50. if (needResize) {
  51. renderer.setSize(width, height, false);
  52. }
  53. return needResize;
  54. }
  55. function render(time) {
  56. time *= 0.001;
  57. if (resizeRendererToDisplaySize(renderer)) {
  58. camera.aspect = state.width / state.height;
  59. camera.updateProjectionMatrix();
  60. }
  61. cubes.forEach((cube, ndx) => {
  62. const speed = 1 + ndx * .1;
  63. const rot = time * speed;
  64. cube.rotation.x = rot;
  65. cube.rotation.y = rot;
  66. });
  67. renderer.render(scene, camera);
  68. requestAnimationFrame(render);
  69. }
  70. requestAnimationFrame(render);
  71. }
  72. function size(data) {
  73. state.width = data.width;
  74. state.height = data.height;
  75. }
  76. const handlers = {
  77. main,
  78. size,
  79. };
  80. self.onmessage = function(e) {
  81. const fn = handlers[e.data.type];
  82. if (!fn) {
  83. throw new Error('no handler for type: ' + e.data.type);
  84. }
  85. fn(e.data);
  86. };