shared-cubes.js 2.1 KB

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