2
0

webxr_ar_cones.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js ar - cones</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> ar - cones<br/>(Chrome Android 81+)
  12. </div>
  13. <script type="module">
  14. import * as THREE from '../build/three.module.js';
  15. import { ARButton } from './jsm/webxr/ARButton.js';
  16. let camera, scene, renderer;
  17. let controller;
  18. init();
  19. animate();
  20. function init() {
  21. const container = document.createElement( 'div' );
  22. document.body.appendChild( container );
  23. scene = new THREE.Scene();
  24. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 20 );
  25. const light = new THREE.HemisphereLight( 0xffffff, 0xbbbbff, 1 );
  26. light.position.set( 0.5, 1, 0.25 );
  27. scene.add( light );
  28. //
  29. renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
  30. renderer.setPixelRatio( window.devicePixelRatio );
  31. renderer.setSize( window.innerWidth, window.innerHeight );
  32. renderer.xr.enabled = true;
  33. container.appendChild( renderer.domElement );
  34. //
  35. document.body.appendChild( ARButton.createButton( renderer ) );
  36. //
  37. const geometry = new THREE.CylinderGeometry( 0, 0.05, 0.2, 32 ).rotateX( Math.PI / 2 );
  38. function onSelect() {
  39. const material = new THREE.MeshPhongMaterial( { color: 0xffffff * Math.random() } );
  40. const mesh = new THREE.Mesh( geometry, material );
  41. mesh.position.set( 0, 0, - 0.3 ).applyMatrix4( controller.matrixWorld );
  42. mesh.quaternion.setFromRotationMatrix( controller.matrixWorld );
  43. scene.add( mesh );
  44. }
  45. controller = renderer.xr.getController( 0 );
  46. controller.addEventListener( 'select', onSelect );
  47. scene.add( controller );
  48. //
  49. window.addEventListener( 'resize', onWindowResize );
  50. }
  51. function onWindowResize() {
  52. camera.aspect = window.innerWidth / window.innerHeight;
  53. camera.updateProjectionMatrix();
  54. renderer.setSize( window.innerWidth, window.innerHeight );
  55. }
  56. //
  57. function animate() {
  58. renderer.setAnimationLoop( render );
  59. }
  60. function render() {
  61. renderer.render( scene, camera );
  62. }
  63. </script>
  64. </body>
  65. </html>