textured-cube.html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 - Textured Cube</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <script type="module">
  24. import * as THREE from '../../build/three.module.js';
  25. function main() {
  26. const canvas = document.querySelector('#c');
  27. const renderer = new THREE.WebGLRenderer({canvas});
  28. const fov = 75;
  29. const aspect = 2; // the canvas default
  30. const near = 0.1;
  31. const far = 5;
  32. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  33. camera.position.z = 2;
  34. const scene = new THREE.Scene();
  35. const boxWidth = 1;
  36. const boxHeight = 1;
  37. const boxDepth = 1;
  38. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  39. const cubes = []; // just an array we can use to rotate the cubes
  40. const loader = new THREE.TextureLoader();
  41. const material = new THREE.MeshBasicMaterial({
  42. map: loader.load('resources/images/wall.jpg'),
  43. });
  44. const cube = new THREE.Mesh(geometry, material);
  45. scene.add(cube);
  46. cubes.push(cube); // add to our list of cubes to rotate
  47. function resizeRendererToDisplaySize(renderer) {
  48. const canvas = renderer.domElement;
  49. const width = canvas.clientWidth;
  50. const height = canvas.clientHeight;
  51. const needResize = canvas.width !== width || canvas.height !== height;
  52. if (needResize) {
  53. renderer.setSize(width, height, false);
  54. }
  55. return needResize;
  56. }
  57. function render(time) {
  58. time *= 0.001;
  59. if (resizeRendererToDisplaySize(renderer)) {
  60. const canvas = renderer.domElement;
  61. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  62. camera.updateProjectionMatrix();
  63. }
  64. cubes.forEach((cube, ndx) => {
  65. const speed = .2 + ndx * .1;
  66. const rot = time * speed;
  67. cube.rotation.x = rot;
  68. cube.rotation.y = rot;
  69. });
  70. renderer.render(scene, camera);
  71. requestAnimationFrame(render);
  72. }
  73. requestAnimationFrame(render);
  74. }
  75. main();
  76. </script>
  77. </html>