Как подключить файл js к проекту
Пытаюсь подключить orbit control но почему то не выходит
function init() {
// прослушивание событий изменения размера
window.addEventListener('resize', onResize, false);
var camera;
var scene;
var renderer;
var trackballControls;
var clock;
var control;
// инициализировать статистику
var stats = initStats();
// создаëм сцену, которая будет содержать все наши элементы, такие как объекты, камеры и источники света.
scene = new THREE.Scene();
// создайте камеру, которая определяет, куда мы смотрим.
// camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera = initCamera(new THREE.Vector3(50, 120, 220));
// camera.position.set(20, 0, 150);
// создайте рендеринг и установите размер
renderer = new THREE.WebGLRenderer();
renderer.antialias = true; // чтоб муравьи не бегали
renderer.setClearColor(new THREE.Color(0x497580)); // поставмл пока серо-синий фон
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
// инициализируйте элементы управления трекболом и часы, которые необходимы
trackballControls = initTrackballControls(camera, renderer);
clock = new THREE.Clock();
control = new OrbitControls( camera, renderer.domElement );
control.listenToKeyEvents( window ); // optional
//control.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)
control.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
control.dampingFactor = 0.05;
control.screenSpacePanning = false;
control.minDistance = 100;
control.maxDistance = 500;
control.maxPolarAngle = Math.PI / 2;
// рисую квадраты осей
//--------------Создаем объект-------------------
var osxyGeometry = new THREE.Geometry();//Производная фигура
osxyGeometry.vertices.push(new THREE.Vector3(-10, 10, 0));//Указываем вектор первой точки
osxyGeometry.vertices.push(new THREE.Vector3(10, 10, 0));//Указываем вектор второй точки
osxyGeometry.vertices.push(new THREE.Vector3(10, -10, 0));
osxyGeometry.vertices.push(new THREE.Vector3(-10, -10, 0));
osxyGeometry.vertices.push(new THREE.Vector3(-10, 10, 0));
var osxyMaterial = new THREE.LineBasicMaterial({color:0x7457bd, linewidth:1});
var osxy = new THREE.Line(osxyGeometry, osxyMaterial);//Создаем линию из созданной геометрии
//--------------Добавление вывод-----------------
scene.add(osxy);//Добавляем объект на сцену
//--------------Создаем объект-------------------
var osyzGeometry = new THREE.Geometry();//Производная фигура
osyzGeometry.vertices.push(new THREE.Vector3(0, -10, 10));//Указываем вектор первой точки
osyzGeometry.vertices.push(new THREE.Vector3(0, 10, 10));//Указываем вектор второй точки
osyzGeometry.vertices.push(new THREE.Vector3(0, 10, -10));
osyzGeometry.vertices.push(new THREE.Vector3(0, -10, -10));
osyzGeometry.vertices.push(new THREE.Vector3(0, -10, 10));
var osyzMaterial = new THREE.LineBasicMaterial({color:0x3d803d, linewidth:1});
var osyz = new THREE.Line(osyzGeometry, osyzMaterial);//Создаем линию из созданной геометрии
//--------------Добавление вывод-----------------
scene.add(osyz);//Добавляем объект на сцену
//--------------Создаем объект-------------------
var osxzGeometry = new THREE.Geometry();//Производная фигура
osxzGeometry.vertices.push(new THREE.Vector3(-10, 0, 10));//Указываем вектор первой точки
osxzGeometry.vertices.push(new THREE.Vector3(10, 0, 10));//Указываем вектор второй точки
osxzGeometry.vertices.push(new THREE.Vector3(10, 0, -10));
osxzGeometry.vertices.push(new THREE.Vector3(-10, 0, -10));
osxzGeometry.vertices.push(new THREE.Vector3(-10, 0, 10));
var osxzMaterial = new THREE.LineBasicMaterial({color:0xab5641, linewidth:1});
var osxz = new THREE.Line(osxzGeometry, osxzMaterial);//Создаем линию из созданной геометрии
//--------------Добавление вывод-----------------
scene.add(osxz);//Добавляем объект на сцену
// создайте наземную плоскость
//var planeGeometry = new THREE.PlaneGeometry(60, 60, 1, 1);
//var planeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
//var plane = new THREE.Mesh(planeGeometry, planeMaterial);
//plane.receiveShadow = true;
// поверните и расположите плоскость
//plane.rotation.x = -0.5 * Math.PI;
//plane.position.x = 15;
//plane.position.y = 0;
//plane.position.z = 0;
// add the plane to the scene
//scene.add(plane);
// добавляем оси и коордиеационные сетки
var axes = new THREE.AxisHelper(30);
axes.position.set( 0,0,0 ); scene.add(axes);
var gridXZ = new THREE.GridHelper(100, 20);
gridXZ.setColors( new THREE.Color(0x006600),
new THREE.Color(0x006600) );
gridXZ.position.set( 100,0,100 );
scene.add(gridXZ);
var gridXY = new THREE.GridHelper(100, 20);
gridXY.position.set( 100,100,0 );
gridXY.rotation.x = Math.PI/2;
gridXY.setColors( new THREE.Color(0x000066),
new THREE.Color(0x000066) );
scene.add(gridXY);
var gridYZ = new THREE.GridHelper(100, 20);
gridYZ.position.set( 0,100,100 );
gridYZ.rotation.z = Math.PI/2;
gridYZ.setColors( new THREE.Color(0x660000),
new THREE.Color(0x660000) );
scene.add(gridYZ);
// расположите и направьте камеру в центр сцены
//camera.position.x = -30;
// camera.position.y = 40;
// camera.position.z = 30;
// camera.lookAt(scene.position);
camera.position.set(20, 0, 150);
// добавьте тонкое окружающее освещение
var ambienLight = new THREE.AmbientLight(0x353535);
scene.add(ambienLight);
// добавьте подсветку для теней
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(-10, 20, -5);
spotLight.castShadow = true;
scene.add(spotLight);
// добавьте выходные данные средства визуализации в html-элемент
document.getElementById("webgl-output").appendChild(renderer.domElement);
// вызовите функцию рендеринга
var step = 0;
var controls = new function () {
this.rotationSpeed = 0.02;
this.bouncingSpeed = 0.03;
};
var controls1 = new function () {
this.site = "hangge.com";
};
var controls2 = new function () {
this.rotationSpeed = 0;
};
var gui = new dat.GUI();
const geometryFolder = gui.addFolder("камера");
geometryFolder.add(controls2, "rotationSpeed", { 'стоп': 0, 'медленно': 0.02, 'быстро': 5 }).name("скорость");
geometryFolder.add(controls, 'rotationSpeed', 0, 0.5);
geometryFolder.add(controls, 'bouncingSpeed', 0, 0.5);
const primitiveFolder = gui.addFolder("примитивы");
// primitiveFolder.add(controls2, 'rotationSpeed', { Stopped: 0, Slow: 0.02, Fast: 5 });
animate();
// render();
function animate() {
requestAnimationFrame( animate );
control.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true
render();
}
function render() {
stats.update();
var delta = clock.getDelta();
trackballControls.update(delta);
requestAnimationFrame(render);
renderer.render(scene, camera);
// обновите статистику и элементы управления
// trackballControls.update(clock.getDelta());
// stats.update();
// рендеринг с использованием requestAnimationFrame
// requestAnimationFrame(render);
//renderer.render(scene, camera);
}
function onResize() {
//camera.aspect = window.innerWidth / window.innerHeight;
// camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
}
Делал по примеру https://threejs.org/examples/?q=orbit#misc_controls_orbit
<!DOCTYPE html>
<html>
<head>
<title>мое_изделие</title>
<meta charset="UTF-8" />
<script type="text/javascript" charset="UTF-8" src="../../libs/three/three.js"></script>
<script type="text/javascript" charset="UTF-8" src="../../libs/three/controls/TrackballControls.js"></script>
<script type="text/javascript" charset="UTF-8" src="../../libs/three/controls/OrbitControls.js"></script>
<script type="text/javascript" src="../../libs/util/Stats.js"></script>
<script type="text/javascript" src="../../libs/util/dat.gui.js"></script>
<script type="text/javascript" src="../js/util.js"></script>
<script type="text/javascript" src="./js/my.js"></script>
<link rel="stylesheet" href="../../css/default.css">
</head>
<body>
<div id="webgl-output"></div>
<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">
(function () {
// your page initialization code here
// the DOM will be available here
init()
})();
</script>
</body>
</html>
Почему-то браузер не видит, не знаю почему.
<script type="text/javascript" charset="UTF-8"
src="../../libs/three/controls/OrbitControls.js">
</script>
Сделал по примеру @SaNFeeD
Увы не заработало.
<!DOCTYPE html>
<html>
<head>
<title>мое_изделие</title>
<meta charset="UTF-8" />
<script type="text/javascript" charset="UTF-8" src="../../libs/three/three.js"></script>
<script type="text/javascript" charset="UTF-8" src="../../libs/three/controls/TrackballControls.js"></script>
<script type="text/javascript" charset="UTF-8" src="../../libs/three/controls/OrbitControls.js"></script>
<script type="text/javascript" src="../../libs/util/Stats.js"></script>
<script type="text/javascript" src="../../libs/util/dat.gui.js"></script>
<script type="text/javascript" src="../js/util.js"></script>
<script type="module" src="./js/my.js"></script>
<!-- <script type="text/javascript" src="./js/my.js"></script> ранше так было -->
<link rel="stylesheet" href="../../css/default.css">
</head>
<body>
<div id="webgl-output"></div>
<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">
(function () {
// your page initialization code here
// the DOM will be available here
init()
})();
</script>
</body>
</html>
My.js
//import * as THREE from 'three';
//#include "OrbitControls.js"
//import { create, all } from 'orbitcontrolsjs'
import { OrbitControls } from '../../libs/three/controls/OrbitControls.js';
function init() {
// прослушивание событий изменения размера
window.addEventListener('resize', onResize, false);
var camera;
var scene;
var renderer;
var trackballControls;
var clock;
var control;
// инициализировать статистику
var stats = initStats();
// создаëм сцену, которая будет содержать все наши элементы, такие как объекты, камеры и источники света.
scene = new THREE.Scene();
// создайте камеру, которая определяет, куда мы смотрим.
// camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera = initCamera(new THREE.Vector3(50, 120, 220));
// camera.position.set(20, 0, 150);
// создайте рендеринг и установите размер
renderer = new THREE.WebGLRenderer();
renderer.antialias = true; // чтоб муравьи не бегали
renderer.setClearColor(new THREE.Color(0x497580)); // поставмл пока серо-синий фон
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
// инициализируйте элементы управления трекболом и часы, которые необходимы
trackballControls = initTrackballControls(camera, renderer);
clock = new THREE.Clock();
control = new OrbitControls( camera, renderer.domElement );
control.listenToKeyEvents( window ); // optional
//control.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)
control.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
control.dampingFactor = 0.05;
control.screenSpacePanning = false;
control.minDistance = 100;
control.maxDistance = 500;
control.maxPolarAngle = Math.PI / 2;
// рисую квадраты осей
//--------------Создаем объект-------------------
var osxyGeometry = new THREE.Geometry();//Производная фигура
osxyGeometry.vertices.push(new THREE.Vector3(-10, 10, 0));//Указываем вектор первой точки
osxyGeometry.vertices.push(new THREE.Vector3(10, 10, 0));//Указываем вектор второй точки
osxyGeometry.vertices.push(new THREE.Vector3(10, -10, 0));
osxyGeometry.vertices.push(new THREE.Vector3(-10, -10, 0));
osxyGeometry.vertices.push(new THREE.Vector3(-10, 10, 0));
var osxyMaterial = new THREE.LineBasicMaterial({color:0x7457bd, linewidth:1});
var osxy = new THREE.Line(osxyGeometry, osxyMaterial);//Создаем линию из созданной геометрии
//--------------Добавление вывод-----------------
scene.add(osxy);//Добавляем объект на сцену
//--------------Создаем объект-------------------
var osyzGeometry = new THREE.Geometry();//Производная фигура
osyzGeometry.vertices.push(new THREE.Vector3(0, -10, 10));//Указываем вектор первой точки
osyzGeometry.vertices.push(new THREE.Vector3(0, 10, 10));//Указываем вектор второй точки
osyzGeometry.vertices.push(new THREE.Vector3(0, 10, -10));
osyzGeometry.vertices.push(new THREE.Vector3(0, -10, -10));
osyzGeometry.vertices.push(new THREE.Vector3(0, -10, 10));
var osyzMaterial = new THREE.LineBasicMaterial({color:0x3d803d, linewidth:1});
var osyz = new THREE.Line(osyzGeometry, osyzMaterial);//Создаем линию из созданной геометрии
//--------------Добавление вывод-----------------
scene.add(osyz);//Добавляем объект на сцену
//--------------Создаем объект-------------------
var osxzGeometry = new THREE.Geometry();//Производная фигура
osxzGeometry.vertices.push(new THREE.Vector3(-10, 0, 10));//Указываем вектор первой точки
osxzGeometry.vertices.push(new THREE.Vector3(10, 0, 10));//Указываем вектор второй точки
osxzGeometry.vertices.push(new THREE.Vector3(10, 0, -10));
osxzGeometry.vertices.push(new THREE.Vector3(-10, 0, -10));
osxzGeometry.vertices.push(new THREE.Vector3(-10, 0, 10));
var osxzMaterial = new THREE.LineBasicMaterial({color:0xab5641, linewidth:1});
var osxz = new THREE.Line(osxzGeometry, osxzMaterial);//Создаем линию из созданной геометрии
//--------------Добавление вывод-----------------
scene.add(osxz);//Добавляем объект на сцену
// создайте наземную плоскость
//var planeGeometry = new THREE.PlaneGeometry(60, 60, 1, 1);
//var planeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
//var plane = new THREE.Mesh(planeGeometry, planeMaterial);
//plane.receiveShadow = true;
// поверните и расположите плоскость
//plane.rotation.x = -0.5 * Math.PI;
//plane.position.x = 15;
//plane.position.y = 0;
//plane.position.z = 0;
// add the plane to the scene
//scene.add(plane);
// добавляем оси и коордиеационные сетки
var axes = new THREE.AxisHelper(30);
axes.position.set( 0,0,0 ); scene.add(axes);
var gridXZ = new THREE.GridHelper(100, 20);
gridXZ.setColors( new THREE.Color(0x006600),
new THREE.Color(0x006600) );
gridXZ.position.set( 100,0,100 );
scene.add(gridXZ);
var gridXY = new THREE.GridHelper(100, 20);
gridXY.position.set( 100,100,0 );
gridXY.rotation.x = Math.PI/2;
gridXY.setColors( new THREE.Color(0x000066),
new THREE.Color(0x000066) );
scene.add(gridXY);
var gridYZ = new THREE.GridHelper(100, 20);
gridYZ.position.set( 0,100,100 );
gridYZ.rotation.z = Math.PI/2;
gridYZ.setColors( new THREE.Color(0x660000),
new THREE.Color(0x660000) );
scene.add(gridYZ);
// расположите и направьте камеру в центр сцены
//camera.position.x = -30;
// camera.position.y = 40;
// camera.position.z = 30;
// camera.lookAt(scene.position);
camera.position.set(20, 0, 150);
// добавьте тонкое окружающее освещение
var ambienLight = new THREE.AmbientLight(0x353535);
scene.add(ambienLight);
// добавьте подсветку для теней
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(-10, 20, -5);
spotLight.castShadow = true;
scene.add(spotLight);
// добавьте выходные данные средства визуализации в html-элемент
document.getElementById("webgl-output").appendChild(renderer.domElement);
// вызовите функцию рендеринга
var step = 0;
var controls = new function () {
this.rotationSpeed = 0.02;
this.bouncingSpeed = 0.03;
};
var controls1 = new function () {
this.site = "hangge.com";
};
var controls2 = new function () {
this.rotationSpeed = 0;
};
var gui = new dat.GUI();
const geometryFolder = gui.addFolder("камера");
geometryFolder.add(controls2, "rotationSpeed", { 'стоп': 0, 'медленно': 0.02, 'быстро': 5 }).name("скорость");
geometryFolder.add(controls, 'rotationSpeed', 0, 0.5);
geometryFolder.add(controls, 'bouncingSpeed', 0, 0.5);
const primitiveFolder = gui.addFolder("примитивы");
// primitiveFolder.add(controls2, 'rotationSpeed', { Stopped: 0, Slow: 0.02, Fast: 5 });
animate();
// render();
function animate() {
requestAnimationFrame( animate );
control.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true
render();
}
function render() {
stats.update();
var delta = clock.getDelta();
trackballControls.update(delta);
requestAnimationFrame(render);
renderer.render(scene, camera);
// обновите статистику и элементы управления
// trackballControls.update(clock.getDelta());
// stats.update();
// рендеринг с использованием requestAnimationFrame
// requestAnimationFrame(render);
//renderer.render(scene, camera);
}
function onResize() {
//camera.aspect = window.innerWidth / window.innerHeight;
// camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
}
Ответы (2 шт):
Ошибка при импорте. В основном файле, с вашим кодом, вы должны импортировать нужную библиотеку.
import * as THREE from 'three';
В файле html необходимо убрать импорт Orbit, а именно вот эту строчку
<script type="text/javascript" charset="UTF-8" src="../../libs/three/controls/OrbitControls.js"></script>
И подключить ваш файл с основным кодом подключить следующим образом.
<script type="module" src="/ваше_имя.js"></script>
Далее все заработает. Более подробная информация есть в документации
P.S
Нашел ошибку. Удалите вызов функции init() в html файле и вынесите ее в ваш файл. И в самом конце вызовите ее
В общем хотел из примера вытянуть, но уже парадигма поменялась. И там новое ядро из за это не удалось запустить.
Вот новый вариант
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - orbit controls</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
<style>
body {
background-color: #ccc;
color: #000;
}
a {
color: #f00;
}
</style>
</head>
<body>
<div id="info">
<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - orbit controls
</div>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"three/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import Stats from 'three/addons/libs/stats.module.js';
let camera, controls, scene, renderer;
let stats, container;
init();
//render(); // remove when using next line for animation loop (requestAnimationFrame)
animate();
function init() {
container = document.getElementById( 'container' );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x94afb5 );
scene.fog = new THREE.FogExp2( 0x94afb5, 0.002 );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
//document.body.appendChild( renderer.domElement );
//container.appendChild( renderer.domElement );
//container=document.body.appendChild( renderer.domElement );
document.body.appendChild( renderer.domElement );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 400, 200, 0 );
// controls
controls = new OrbitControls( camera, renderer.domElement );
controls.listenToKeyEvents( window ); // optional
//controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)
controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false;
controls.minDistance = 100;
controls.maxDistance = 500;
controls.maxPolarAngle = Math.PI / 2;
// world
// рисую квадраты осей
//--------------Создаем объект-------------------
const points = [];
points.push(new THREE.Vector3(-10, 10, 0));
points.push(new THREE.Vector3(10, 10, 0));
points.push(new THREE.Vector3(10, -10, 0));
points.push(new THREE.Vector3(-10, -10, 0));
points.push(new THREE.Vector3(-10, 10, 0));
const osxyMaterial = new THREE.LineBasicMaterial({ color: 0x7457bd, linewidth: 1 });
const osxyGeometry = new THREE.BufferGeometry().setFromPoints(points);
const osxy = new THREE.Line(osxyGeometry, osxyMaterial);
scene.add(osxy);
const points1 = [];
points1.push(new THREE.Vector3(0, -10, 10));//Указываем вектор первой точки
points1.push(new THREE.Vector3(0, 10, 10));//Указываем вектор второй точки
points1.push(new THREE.Vector3(0, 10, -10));
points1.push(new THREE.Vector3(0, -10, -10));
points1.push(new THREE.Vector3(0, -10, 10));
const osxzMaterial = new THREE.LineBasicMaterial({ color: 0x3d803d, linewidth: 1 });
const osxzGeometry = new THREE.BufferGeometry().setFromPoints(points1);
const osxz = new THREE.Line(osxzGeometry, osxzMaterial);
scene.add(osxz);
const points2 = []
points2.push(new THREE.Vector3(-10, 0, 10));//Указываем вектор первой точки
points2.push(new THREE.Vector3(10, 0, 10));//Указываем вектор второй точки
points2.push(new THREE.Vector3(10, 0, -10));
points2.push(new THREE.Vector3(-10, 0, -10));
points2.push(new THREE.Vector3(-10, 0, 10));
const osyzMaterial = new THREE.LineBasicMaterial({ color: 0xab5641, linewidth: 1 })
const osyzGeometry = new THREE.BufferGeometry().setFromPoints(points2)
const osyz = new THREE.Line(osyzGeometry, osyzMaterial)
scene.add(osyz)
// lights
const dirLight1 = new THREE.DirectionalLight( 0xffffff );
dirLight1.position.set( 1, 1, 1 );
scene.add( dirLight1 );
const dirLight2 = new THREE.DirectionalLight( 0x002288 );
dirLight2.position.set( - 1, - 1, - 1 );
scene.add( dirLight2 );
const ambientLight = new THREE.AmbientLight( 0x222222 );
scene.add( ambientLight );
// тут!!! статистика.
stats = new Stats();
//container.appendChild( stats.dom );
document.body.appendChild( stats.dom );
//
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
controls.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true
stats.update();
render();
}
function render() {
stats.update();
renderer.render( scene, camera );
}
</script>
</body>
</html>



