threejs-responsive.js 1.9 KB

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