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