shared-cubes.js 2.0 KB

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