threejs-fundamentals-3-cubes.html 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Fundamentals 3 cubes</title>
  8. </head>
  9. <body>
  10. <canvas id="c"></canvas>
  11. </body>
  12. <script src="resources/threejs/r93/three.min.js"></script>
  13. <script src="resources/threejs-lessons-helper.js"></script> <!-- you can and should delete this script. it is only used on the site to help with errors -->
  14. <script>
  15. 'use strict';
  16. function main() {
  17. const canvas = document.querySelector('#c');
  18. const renderer = new THREE.WebGLRenderer({canvas: canvas});
  19. const fov = 75;
  20. const aspect = 2; // the canvas default
  21. const zNear = 0.1;
  22. const zFar = 5;
  23. const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar);
  24. camera.position.z = 2;
  25. const scene = new THREE.Scene();
  26. const light = new THREE.DirectionalLight(0xffffff, 1);
  27. light.position.set(-1, 2, 4);
  28. scene.add(light);
  29. const boxWidth = 1;
  30. const boxHeight = 1;
  31. const boxDepth = 1;
  32. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  33. function makeInstance(geometry, color, x) {
  34. const material = new THREE.MeshPhongMaterial({color});
  35. const cube = new THREE.Mesh(geometry, material);
  36. scene.add(cube);
  37. cube.position.x = x;
  38. return cube;
  39. }
  40. const cubes = [
  41. makeInstance(geometry, 0x44aa88, 0),
  42. makeInstance(geometry, 0x8844aa, -2),
  43. makeInstance(geometry, 0xaa8844, 2),
  44. ];
  45. function render(time) {
  46. time *= 0.001; // convert time to seconds
  47. cubes.forEach((cube, ndx) => {
  48. const speed = 1 + ndx * .1;
  49. const rot = time * speed;
  50. cube.rotation.x = rot;
  51. cube.rotation.y = rot;
  52. });
  53. renderer.render(scene, camera);
  54. requestAnimationFrame(render);
  55. }
  56. requestAnimationFrame(render);
  57. }
  58. main();
  59. </script>
  60. </html>