threejs-responsive.js 1.9 KB

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