threejs-textured-cube.html 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. 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/r102/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. const material = new THREE.MeshBasicMaterial({
  43. map: loader.load('resources/images/wall.jpg'),
  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. 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>