threejs-fundamentals-3-cubes.html 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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/r102/three.min.js"></script>
  13. <script>
  14. 'use strict';
  15. /* global THREE */
  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 near = 0.1;
  22. const far = 5;
  23. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  24. camera.position.z = 2;
  25. const scene = new THREE.Scene();
  26. {
  27. const color = 0xFFFFFF;
  28. const intensity = 1;
  29. const light = new THREE.DirectionalLight(color, intensity);
  30. light.position.set(-1, 2, 4);
  31. scene.add(light);
  32. }
  33. const boxWidth = 1;
  34. const boxHeight = 1;
  35. const boxDepth = 1;
  36. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  37. function makeInstance(geometry, color, x) {
  38. const material = new THREE.MeshPhongMaterial({color});
  39. const cube = new THREE.Mesh(geometry, material);
  40. scene.add(cube);
  41. cube.position.x = x;
  42. return cube;
  43. }
  44. const cubes = [
  45. makeInstance(geometry, 0x44aa88, 0),
  46. makeInstance(geometry, 0x8844aa, -2),
  47. makeInstance(geometry, 0xaa8844, 2),
  48. ];
  49. function render(time) {
  50. time *= 0.001; // convert time to seconds
  51. cubes.forEach((cube, ndx) => {
  52. const speed = 1 + ndx * .1;
  53. const rot = time * speed;
  54. cube.rotation.x = rot;
  55. cube.rotation.y = rot;
  56. });
  57. renderer.render(scene, camera);
  58. requestAnimationFrame(render);
  59. }
  60. requestAnimationFrame(render);
  61. }
  62. main();
  63. </script>
  64. </html>