textured-cube-wait-for-texture.html 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. 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. loader.load('resources/images/wall.jpg', (texture) => {
  42. const material = new THREE.MeshBasicMaterial({
  43. map: texture,
  44. });
  45. const cube = new THREE.Mesh(geometry, material);
  46. scene.add(cube);
  47. cubes.push(cube); // add to our list of cubes to rotate
  48. });
  49. function resizeRendererToDisplaySize(renderer) {
  50. const canvas = renderer.domElement;
  51. const width = canvas.clientWidth;
  52. const height = canvas.clientHeight;
  53. const needResize = canvas.width !== width || canvas.height !== height;
  54. if (needResize) {
  55. renderer.setSize(width, height, false);
  56. }
  57. return needResize;
  58. }
  59. function render(time) {
  60. time *= 0.001;
  61. if (resizeRendererToDisplaySize(renderer)) {
  62. const canvas = renderer.domElement;
  63. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  64. camera.updateProjectionMatrix();
  65. }
  66. cubes.forEach((cube, ndx) => {
  67. const speed = .2 + ndx * .1;
  68. const rot = time * speed;
  69. cube.rotation.x = rot;
  70. cube.rotation.y = rot;
  71. });
  72. renderer.render(scene, camera);
  73. requestAnimationFrame(render);
  74. }
  75. requestAnimationFrame(render);
  76. }
  77. main();
  78. </script>
  79. </html>