threejs-responsive.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 - Responsive</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/r93/three.min.js"></script>
  23. <script>
  24. 'use strict';
  25. function main() {
  26. const canvas = document.querySelector('#c');
  27. const renderer = new THREE.WebGLRenderer({canvas: canvas});
  28. const fov = 75;
  29. const aspect = 2; // the canvas default
  30. const zNear = 0.1;
  31. const zFar = 5;
  32. const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar);
  33. camera.position.z = 2;
  34. const scene = new THREE.Scene();
  35. const light = new THREE.DirectionalLight(0xffffff, 1);
  36. light.position.set(-1, 2, 4);
  37. scene.add(light);
  38. const boxWidth = 1;
  39. const boxHeight = 1;
  40. const boxDepth = 1;
  41. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  42. function makeInstance(geometry, color, x) {
  43. const material = new THREE.MeshPhongMaterial({color});
  44. const cube = new THREE.Mesh(geometry, material);
  45. scene.add(cube);
  46. cube.position.x = x;
  47. return cube;
  48. }
  49. const cubes = [
  50. makeInstance(geometry, 0x44aa88, 0),
  51. makeInstance(geometry, 0x8844aa, -2),
  52. makeInstance(geometry, 0xaa8844, 2),
  53. ];
  54. function resizeRendererToDisplaySize(renderer) {
  55. const canvas = renderer.domElement;
  56. const width = canvas.clientWidth;
  57. const height = canvas.clientHeight;
  58. const needResize = canvas.width !== width || canvas.height !== height;
  59. if (needResize) {
  60. renderer.setSize(width, height, false);
  61. }
  62. return needResize;
  63. }
  64. function render(time) {
  65. time *= 0.001;
  66. if (resizeRendererToDisplaySize(renderer)) {
  67. const canvas = renderer.domElement;
  68. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  69. camera.updateProjectionMatrix();
  70. }
  71. cubes.forEach((cube, ndx) => {
  72. const speed = 1 + ndx * .1;
  73. const rot = time * speed;
  74. cube.rotation.x = rot;
  75. cube.rotation.y = rot;
  76. });
  77. renderer.render(scene, camera);
  78. requestAnimationFrame(render);
  79. }
  80. requestAnimationFrame(render);
  81. }
  82. main();
  83. </script>
  84. </html>
粤ICP备19079148号