fundamentals-3-cubes.html 1.9 KB

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