shared-cubes.js 2.0 KB

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