webxr_ar_cones.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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/>Enable chrome://flags/#webxr-ar-module<br/>(Chrome Android 80+)
  12. </div>
  13. <script type="module">
  14. import * as THREE from '../build/three.module.js';
  15. import { ARButton } from './jsm/webxr/ARButton.js';
  16. var container;
  17. var camera, scene, renderer;
  18. var controller;
  19. init();
  20. animate();
  21. function init() {
  22. container = document.createElement( 'div' );
  23. document.body.appendChild( container );
  24. scene = new THREE.Scene();
  25. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 20 );
  26. var light = new THREE.HemisphereLight( 0xffffff, 0xbbbbff, 1 );
  27. light.position.set( 0.5, 1, 0.25 );
  28. scene.add( light );
  29. //
  30. renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
  31. renderer.setPixelRatio( window.devicePixelRatio );
  32. renderer.setSize( window.innerWidth, window.innerHeight );
  33. renderer.xr.enabled = true;
  34. container.appendChild( renderer.domElement );
  35. //
  36. document.body.appendChild( ARButton.createButton( renderer ) );
  37. //
  38. var geometry = new THREE.CylinderBufferGeometry( 0, 0.05, 0.2, 32 ).rotateX( Math.PI / 2 );
  39. function onSelect() {
  40. var material = new THREE.MeshPhongMaterial( { color: 0xffffff * Math.random() } );
  41. var mesh = new THREE.Mesh( geometry, material );
  42. mesh.position.set( 0, 0, - 0.3 ).applyMatrix4( controller.matrixWorld );
  43. mesh.quaternion.setFromRotationMatrix( controller.matrixWorld );
  44. scene.add( mesh );
  45. }
  46. controller = renderer.xr.getController( 0 );
  47. controller.addEventListener( 'select', onSelect );
  48. scene.add( controller );
  49. //
  50. window.addEventListener( 'resize', onWindowResize, false );
  51. }
  52. function onWindowResize() {
  53. camera.aspect = window.innerWidth / window.innerHeight;
  54. camera.updateProjectionMatrix();
  55. renderer.setSize( window.innerWidth, window.innerHeight );
  56. }
  57. //
  58. function animate() {
  59. renderer.setAnimationLoop( render );
  60. }
  61. function render() {
  62. renderer.render( scene, camera );
  63. }
  64. </script>
  65. </body>
  66. </html>