2
0

threejs-fundamentals-3-cubes.html 1.8 KB

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