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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 src="resources/threejs/r98/three.min.js"></script>
  23. <script>
  24. 'use strict';
  25. /* global THREE */
  26. function main() {
  27. const canvas = document.querySelector('#c');
  28. const renderer = new THREE.WebGLRenderer({canvas: canvas});
  29. const fov = 75;
  30. const aspect = 2; // the canvas default
  31. const near = 0.1;
  32. const far = 5;
  33. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  34. camera.position.z = 2;
  35. const scene = new THREE.Scene();
  36. const boxWidth = 1;
  37. const boxHeight = 1;
  38. const boxDepth = 1;
  39. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  40. const cubes = []; // just an array we can use to rotate the cubes
  41. const loader = new THREE.TextureLoader();
  42. loader.load('resources/images/wall.jpg', (texture) => {
  43. const material = new THREE.MeshBasicMaterial({
  44. map: texture,
  45. });
  46. const cube = new THREE.Mesh(geometry, material);
  47. scene.add(cube);
  48. cubes.push(cube); // add to our list of cubes to rotate
  49. });
  50. function resizeRendererToDisplaySize(renderer) {
  51. const canvas = renderer.domElement;
  52. const width = canvas.clientWidth;
  53. const height = canvas.clientHeight;
  54. const needResize = canvas.width !== width || canvas.height !== height;
  55. if (needResize) {
  56. renderer.setSize(width, height, false);
  57. }
  58. return needResize;
  59. }
  60. function render(time) {
  61. time *= 0.001;
  62. if (resizeRendererToDisplaySize(renderer)) {
  63. const canvas = renderer.domElement;
  64. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  65. camera.updateProjectionMatrix();
  66. }
  67. cubes.forEach((cube, ndx) => {
  68. const speed = .2 + ndx * .1;
  69. const rot = time * speed;
  70. cube.rotation.x = rot;
  71. cube.rotation.y = rot;
  72. });
  73. renderer.render(scene, camera);
  74. requestAnimationFrame(render);
  75. }
  76. requestAnimationFrame(render);
  77. }
  78. main();
  79. </script>
  80. </html>