dir.by  
Программирование, разработка, тестирование
Three.js - JavaScript библиотека для рисования графики 3D на страницах HTML
Пример "Луна вращается вокруг земли (moon rotate around earth)" библиотека Three.js
  Посмотрели 7331 раз(а)    
 Пример "Луна вращается вокруг земли (moon rotate around earth)" библиотека Three.js 
последнее обновление: 14 октября 2020
Пример смотрим, тестируем
Приближение, удаление от земли - скролинг мышкой
Вращение - нажать на левую клавишу мыши и двигать мышь
Исходный код
  Html  
<!DOCTYPE html>
<html>
     <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
          <title>three.js css2d - label</title>
          <style>
               body
               {
                    background-color: #000;
                    margin: 0;
                    overflow: hidden;
               }

               #info
               {
                    position: absolute;
                    top: 0px;
                    width: 100%;
                    color: #FFF;
                    padding: 5px;
                    font-family: Monospace;
                    font-size: 13px;
                    text-align: center;
                    z-index: 1;
               }

               .label
               {
                    color: #FFF;
                    font-family: sans-serif;
                    padding: 2px;
                    background: rgba( 0, 0, 0, .6 );
               }
          </style>
     </head>

     <body>
          <!-- подключаем библиотеку three.js -->
          <script src="https://dir.by/example_lib/tree_js/three.js"></script>

          <!-- библиотеки дополнительные -->
          <script src="https://dir.by/example_lib/tree_js/OrbitControls.js"></script>
          <script src="https://dir.by/example_lib/tree_js/CSS2DRenderer.js"></script>

          <div id="info"><a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - three.js css2d - label</div>

          <script>
               var camera, scene, renderer, labelRenderer;

               var clock = new THREE.Clock();
               var textureLoader = new THREE.TextureLoader();

               var earth, moon;

               init();
               animate();

               function init() {

                    var EARTH_RADIUS = 1;
                    var MOON_RADIUS = 0.27;

                    camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
                    camera.position.set( 10, 5, 20 );

                    var controls = new THREE.OrbitControls( camera );

                    scene = new THREE.Scene();

                    var dirLight = new THREE.DirectionalLight( 0xffffff );
                    dirLight.position.set( 0, 0, 1 );
                    scene.add( dirLight );

                    var axesHelper = new THREE.AxesHelper( 5 );
                    scene.add( axesHelper );

                    var earthGeometry = new THREE.SphereBufferGeometry( EARTH_RADIUS, 16, 16 );
                    var earthMaterial = new THREE.MeshPhongMaterial( {
                         specular: 0x333333,
                         shininess: 5,
                         map: textureLoader.load( 'https://dir.by/developer/three_js/example_moon_rotate_around_earth/images/earth_atmos_2048.jpg' ),
                         specularMap: textureLoader.load( 'https://dir.by/developer/three_js/example_moon_rotate_around_earth/images/earth_specular_2048.jpg' ),
                         normalMap: textureLoader.load( 'https://dir.by/developer/three_js/example_moon_rotate_around_earth/images/earth_normal_2048.jpg' ),
                         normalScale: new THREE.Vector2( 0.85, 0.85 )
                    } );
                    earth = new THREE.Mesh( earthGeometry, earthMaterial );
                    scene.add( earth );

                    var moonGeometry = new THREE.SphereBufferGeometry( MOON_RADIUS, 16, 16 );
                    var moonMaterial = new THREE.MeshPhongMaterial( {
                         shininess: 5,
                         map: textureLoader.load( 'https://dir.by/developer/three_js/example_moon_rotate_around_earth/images/moon_1024.jpg' )
                    } );
                    moon = new THREE.Mesh( moonGeometry, moonMaterial );
                    scene.add( moon );

                    var earthDiv = document.createElement( 'div' );
                    earthDiv.className = 'label';
                    earthDiv.textContent = 'Earth';
                    earthDiv.style.marginTop = '-1em';
                    var earthLabel = new THREE.CSS2DObject( earthDiv );
                    earthLabel.position.set( 0, EARTH_RADIUS, 0 );
                    earth.add( earthLabel );

                    var moonDiv = document.createElement( 'div' );
                    moonDiv.className = 'label';
                    moonDiv.textContent = 'Moon';
                    moonDiv.style.marginTop = '-1em';
                    var moonLabel = new THREE.CSS2DObject( moonDiv );
                    moonLabel.position.set( 0, MOON_RADIUS, 0 );
                    moon.add( moonLabel );

                    renderer = new THREE.WebGLRenderer();
                    renderer.setPixelRatio( window.devicePixelRatio );
                    renderer.setSize( window.innerWidth, window.innerHeight );
                    document.body.appendChild( renderer.domElement );

                    labelRenderer = new THREE.CSS2DRenderer();
                    labelRenderer.setSize( window.innerWidth, window.innerHeight );
                    labelRenderer.domElement.style.position = 'absolute';
                    labelRenderer.domElement.style.top = 0;
                    document.body.appendChild( labelRenderer.domElement );
               }

               function animate()
               {
                    requestAnimationFrame( animate );

                    var elapsed = clock.getElapsedTime();

                    moon.position.set( Math.sin( elapsed ) * 5, 0, Math.cos( elapsed ) * 5 );

                    renderer.render( scene, camera );
                    labelRenderer.render( scene, camera );
               }
          </script>

     </body>
</html>
На заметку!
Пример локально не работает, потому что ошибка загрузки картинки.

Access to Image at 'Access to Image at 'https://dir.by/developer/three_js/example_moon_rotate_around_earth/images/earth_atmos_2048.jpg' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
 
Error: Access to url at 'http://...' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Решение!
На рабочем столе для иконки Google Chrome добавим парметры: --user-data-dir="C://Chrome dev session" --disable-web-security
Запустим Google Chrome нажав на иконку.
Введем url, ошибки нет.
 
← Предыдущая тема
Пример "Мы сами крутим картинку svg (svg image)" библиотека Three.js
 
Следующая тема →
Пример "Рисуем картину 3D кубиками (interactive voxel painter)" библиотека Three.js
 
Ваши Отзывы ... комментарии ...
   
Вашe имя
Ваш комментарий (www ссылки может добавлять только залогиненный пользователь)

Экскурсии по Москве Экскурсии по Москве: пешеходные, автобусные и речные прогулки на любой вкус
  Объявления  
  Объявления  
 
Что такое Three.js и как скачать?
Пример "Летающие кубики" библиотека Three.js
Пример "Американская горка (roller coaster)" библиотека Three.js
Пример "Вращающийся куб с текстурой (rotate cube)" библиотека Three.js
Пример "Мы сами крутим картинку svg (svg image)" библиотека Three.js
Пример "Луна вращается вокруг земли (moon rotate around earth)" библиотека Three.js
Пример "Рисуем картину 3D кубиками (interactive voxel painter)" библиотека Three.js
Пример "Шарики с эффектом отражения (effects anaglyph)" библиотека Three.js
Создаем свой файл .js Файл содержит объект с экспортными переменными и функциями

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика