<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<script src="https://meadowdecor.jackzc.com/smple/node_modules/three/build/three.min.js"></script>
<script src="https://meadowdecor.jackzc.com/smple/node_modules/three/examples/js/controls/OrbitControls.js"></script>
<script src="https://meadowdecor.jackzc.com/smple/node_modules/three/examples/js/controls/TrackballControls.js"></script>
<script src="https://meadowdecor.jackzc.com/smple/node_modules/three/examples/js/loaders/OBJLoader.js"></script>
<script>
const height = window.innerHeight;
const width = window.innerWidth;
const texture_file = 'https://meadowdecor.jackzc.com/smple/source/texture.jpg';
const model_file = 'https://meadowdecor.jackzc.com/smple/source/5.obj';
/**
* Generate a scene object with a background color
**/
function createScene() {
var scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
return scene;
}
/**
* Generate the camera to be used in the scene. Camera args:
* [0] field of view: identifies the portion of the scene
* visible at any time (in degrees)
* [1] aspect ratio: identifies the aspect ratio of the
* scene in width/height
* [2] near clipping plane: objects closer than the near
* clipping plane are culled from the scene
* [3] far clipping plane: objects farther than the far
* clipping plane are culled from the scene
**/
function createCamera() {
const aspectRatio = width / height;
const camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 1000);
camera.position.set(0, 1, 10);
return camera;
}
/**
* Generate the light to be used in the scene. Light args:
* [0]: Hexadecimal color of the light
* [1]: Numeric value of the light's strength/intensity
* [2]: The distance from the light where the intensity is 0
* @param {obj} scene: the current scene object
**/
function createLights(scene) {
const light1 = new THREE.PointLight(0xffffff, 1, 0);
light1.position.set(1, 1, 1);
scene.add(light1);
// An ambient light
const light2 = new THREE.AmbientLight(0x111111);
scene.add(light2);
}
/**
* Generate the renderer to be used in the scene
**/
function createRenderer() {
// Create the canvas with a renderer
const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
// Add support for retina displays
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setClearColor("#fff");
// Specify the size of the canvas
renderer.setSize(width, height);
// Add the canvas to the DOM
document.body.appendChild(renderer.domElement);
return renderer;
}
/**
* Generate the controls to be used in the scene
* @param {obj} camera: the three.js camera for the scene
* @param {obj} renderer: the three.js renderer for the scene
**/
function createControls(camera, renderer) {
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.zoomSpeed = 0.4;
controls.panSpeed = 0.4;
return controls;
}
function createTexture() {
var texture_loader = new THREE.TextureLoader();
var texture = texture_loader.load(texture_file);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1, 1);
texture.needsUpdate = true;
}
/**
* Load object
**/
function loadModel() {
const loader = new THREE.OBJLoader();
loader.load(model_file, function (object) {
// object.rotation.z = Math.PI;
// object.scale.set(2,2,2);
// object.position.set(1, 1, 1);
object.frustumCulled = false;
scene.add(object);
});
}
/**
* Render!
**/
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
controls.update();
};
//==========================================================================================//
var scene = createScene();
var camera = createCamera();
var renderer = createRenderer();
var controls = createControls(camera, renderer);
createLights(scene);
loadModel(scene);
render();
</script>
</body>
</html>
Только начав изучать ThreeJS, я скачал файл obj и попытался загрузить его на веб-страницу с помощью ThreeJS, это сработало! Однако это работает не так, как я хочу, я ожидаю, что объект отображается в середине моего экрана, но это не так. Я должен удерживать левую кнопку мыши и тянуть ее вправо, тогда объект отображается! И это меньше, чем я ожидал!
Вот код ниже, и, как я уже говорил, я очень новичок в ThreeJS, я потратил 2 дня, пытаясь понять это, и у меня ничего не вышло. СПАСИБО за любую помощь.
PS:
Обновлять:
Модель ведет себя так, как будто использует координату моей мыши в качестве источника, но с расстоянием. кликните сюда, чтобы увидеть эффект (вы должны удерживать левую кнопку мыши и перемещать ее, чтобы найти модель).
Во-первых, чтобы решить, что объект слишком мал, вы можете масштабировать его:
model.scale.set(2, 2, 2); //Double
Из-за того, что ваша модель не центрирована, она может быть не в начале координат (когда она была создана). Вы можете исправить модель или изменить положение модели в three.js
с помощью model.position
. Если ваш объект не отображается должным образом, попробуйте добавить:
object.frustumCulled = false;
Это должно сделать это ~
Спасибо за вашу помощь, я предполагаю, что мне следует поместить эти две строки здесь: function loadModel() { const loader = new THREE.OBJLoader(); loader.load (файл_модели, функция (объект) { object.scale.set (2,2,2); object.frustrumCulled = false; scene.add (объект); }); } К сожалению, это не работает.
Давайте решать одну проблему за раз. Ваша модель кажется больше?
Я тоже сделал опечатку. frustrumCulled
должно быть frustumCulled
. я отредактировал свой ответ
На самом деле он не выглядит больше, на экране ничего не появляется, просто черный фон после того, как я добавил первую строку: object.scale.set(2,2,2).
Это может быть из-за culling
. Вы исправили мою опечатку?
Я не знаю, моя ли это иллюзия, похоже, что этот объект использует координату моей мыши в качестве источника, но с расстоянием.
Не могли бы вы предоставить фрагмент, чтобы я мог взглянуть?
Let us continue this discussion in chat.
OK, after almost a week of struggling, I finally get it to work. It's actually quite simple because the 3D model I downloaded was not centered! After trying another model which centered, all works fine.
You actually pointed out the problem but I was just confused with something else, I'm going to mark your post as an answer, Very much appreciated your help!
Взгляните на мой ответ