Adjusting the Camera in three.js

I'm relatively new to three.js and webgl programming. I managed to create a box in three.js, which is functioning correctly. However, I encountered an issue where the box disappears when I try setting the camera position along the z-axis (e.g., camera.position.z = 2;). Can someone help explain why this is happening and advise me on how to set the camera position properly?

Feel free to uncomment the camera.position.z = 2; in this example

function init() {

    var scene = new THREE.Scene();

    var box = getBox(1, 1, 1);

    scene.add(box);

    var camera = new THREE.Camera(45, window.innerWidth/window.innerHeight, 1, 1000 );
    //camera.position.z = 2;

    var renderer = new THREE.WebGLRenderer();

    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById("webgl").appendChild(renderer.domElement);

    renderer.render(scene, camera);
}

function getBox(w, h, d) {
    var geometry = new THREE.BoxGeometry(w, h, d);
    var material = new THREE.MeshBasicMaterial({
        color : 0x00ff00
    });

    var mesh = new THREE.Mesh(geometry, material);

    return mesh;
} 

init();

Answer №1

Perhaps you're unsure whether to use an orthographic camera or a perspective camera for this particular scene. To specify the type of camera, make sure to include it in your code (e.g., THREE.PerspectiveCamera(...)). I also made some adjustments to ensure that the camera is properly configured, such as setting the "LookAt" point to (0,0,0) and assigning an actual position to the camera using the THREE.Vector3.set(...) method.

Below are the modifications I made to your code:

function init() {

var scene = new THREE.Scene();

var box = getBox(1, 1, 1);

scene.add(box);

var camera = new THREE.PerspectiveCamera(70, 
window.innerWidth/window.innerHeight, 0.1, 1000 ); // Specify camera type like this
camera.position.set(0,2.5,2.5); // Set position like this
camera.lookAt(new THREE.Vector3(0,0,0)); // Set look at coordinate like this

var renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("webgl").appendChild(renderer.domElement);

renderer.render(scene, camera);
}

function getBox(w, h, d) {
var geometry = new THREE.BoxGeometry(w, h, d);
var material = new THREE.MeshBasicMaterial({
    color : 0x00ff00
});

var mesh = new THREE.Mesh(geometry, material);

return mesh;
} 

init();

Answer №2

Experiment with

camera.position.set( <X> , <Y> , <Z> );

Remember that <X> and <Z> represent 2D positions, while <Y> signifies the height.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to divide a single array into two separate arrays based on a specific element?

My goal is to create an interactive graph using plotly.js. I have an array named data that contains all the information needed for the graph. However, I want users to be able to select specific elements to display on the graph. To achieve this functionalit ...

Having trouble with expanding rows in a data table on a shiny application when clicking? Here are some solutions to help you fix it!

I have developed a code in shiny R to generate a data table that expands to display child rows when a row is clicked. However, the expansion feature is only working for the last row of the table. For all previous rows, only the headers of the child table a ...

What is the best way to execute tests in different environments with Protractor?

Is it possible to execute specifications in various environments? Maybe by adjusting the protractor-config file? Could we do something along the lines of specs: ['../tests/*.js', server1], ['../more_tests/*.js', server2] within the ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

Tips for relocating a popup window''s position

A situation has arisen in my application where a popup window is opened with the following code: function newPopup(url, windowName) { window.open(url,windowName,'height=768,width=1366,left=10,top=10,titlebar=no,toolbar=no,menubar=no,location=no,d ...

What are the best ways to incorporate a theme into your ReactJS project?

Looking to create a context for applying dark or light themes in repositories without the need for any manual theme change buttons. The goal is to simply set the theme and leave it as is. Currently, I have a context setup like this: import { createContext ...

Having trouble opening the prompt window by clicking on the button

I have been given an assignment to check if a given number is an Armstrong number. However, I am facing an issue where the prompt window does not appear when I click the button. This issue only arises when the rest of the function is written out. If the ...

Attempting to set up Prettier in my VSCode environment

I've been delving into JavaScript with the guidance of "Morten Rand-Hendriksen" on LinkedIn Learning. The instructor emphasized the importance of installing "Prettier" in our VSCode environment. Following his instructions, I headed to the "Extensions" ...

Is there a child missing? If so, add a class

I need to add the class span.toggle if the parent element of li does not have a child ul element. click here to view on codepen Snippet of HTML: <html lang="en"> <head> <meta charset="UTF-8> <title>No Title</title>& ...

Establish a pathway based on an item on the list

I need to create a functionality where I can click on a fruit in a list to open a new route displaying the description of that fruit. Can someone guide me on how to set up the route to the 'productDescription.ejs' file? app.js: const express = ...

JavaScript code for client-side implementation using Node.js

As I work on developing a web application, I encounter the need to interact with an API that lacks JSONP/CORS support. Initially, my solution was to establish a server with PHP code and utilize ajax calls. However, my discovery of this node module offers ...

Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code: enum UserRole { CONSULTANT, MANAGER, ... } There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user: [ "CONSU ...

Deliver the Stripe API response from the backend to the frontend page

I'm struggling to retrieve the response object from Stripe after creating a subscription using npm. import Stripe from 'stripe'; const key = require("stripe")("XXXXXXXXXXXXXXXXX"); export function subscribe(cus, items) { key.subscription ...

Access Azure-Active Directory through cypress tests

Currently, I'm faced with the task of creating automated tests for an application that requires login to Azure Active Directory. These tests are being written using Cypress and TypeScript. In search of a solution, I am seeking advice on how to execute ...

Arrange the elements in an array by applying a formula that takes into account information from two separate arrays

Currently, I'm in the process of creating a website dedicated to reviewing films, blogs, and other content using React. One of the features I have already implemented is basic sorting functionality. Users can sort content based on a single field such ...

Creating unit tests for linked functions in Node.js using Jest

Hey there! I'm looking to test a function using Jest that involves token verification and requires 3 parameters. Here's the code for the function: const verifyToken = (req, res, next) => { // Checking for token in header or URL parameter ...

Dropdown Placement Based on Button Click

Looking to create an interactive dropdown menu with the Alloy UI Dropdown Component that appears when a user clicks on one of four buttons. The goal is for this dropdown to be positioned to the left of the clicked button. var toolsDropdown = new Y.Dropdow ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

Troubleshoot: JQuery unable to change background color in code

Is there a way to use JQuery to cycle through an array of colors and change the background color of a page whenever a specific button is clicked? I've tried implementing it with the following code, but it doesn't seem to work as expected. Here&a ...