Placing a three-dimensional object in the corners of the canvas using three.js

I'm trying to position a 3D object in either corner of my canvas automatically, regardless of its size.
https://i.sstatic.net/IWgr1.png

After finding a solution on stackoverflow:

I implemented the following code for my object:

mesh.position.set(-(window.innerWidth), (window.innerHeight), 0)

This resulted in only part of the object being visible, like this:
https://i.sstatic.net/jKrJM.png

I want the object to be fully visible and positioned consistently across different canvas sizes, especially for mobile use, like this:
https://i.sstatic.net/vv8lT.png

I have also included an example of my setup here: https://jsfiddle.net/w9914420/dez9k31m/

If anyone can provide some guidance on how to achieve this, I would greatly appreciate it. Thank you.

Answer №1

Utilize the THREE.Raycaster() in conjunction with THREE.Plane():

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.set(0, 5, 10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));

var box = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshLambertMaterial({
  color: "green"
}));
scene.add(box);

var plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 0, 1), new THREE.Vector3(0, 0, 1));

btnMove.addEventListener("click", onClick, false);

var raycaster = new THREE.Raycaster();
var corner = new THREE.Vector2();
var cornerPoint = new THREE.Vector3();

function onClick() {
  corner.set(-1, -1); // NDC of the bottom-left corner
  raycaster.setFromCamera(corner, camera);
  raycaster.ray.intersectPlane(plane, cornerPoint);
  box.position.copy(cornerPoint)
    .add(new THREE.Vector3(1, 1, -1)); // align the position of the box
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}

#btnMove {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<button id="btnMove">Move bottom-left</button>

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

I encountered an issue when trying to launch my React application, as the CMD displayed an npm error message stating 'npm error! missing script:start'. Can someone offer assistance with this problem?

view image details Despite spending countless hours searching through past responses and attempting to resolve this issue, I have been unsuccessful. Upon entering 'npm create-react-app' in the terminal and navigating to the correct directory, I ...

Displaying a Dynamic Loading Animation While Making an AJAX Call with jQuery

When a user clicks on the active status button, it should switch to inactive with a red color, and vice versa. Currently, I can update my status in the backend, but I have to refresh the page to see the changes every time! My requirement is that during t ...

Detecting the specific button that was selected with PHP

I am in the process of developing a website for a production company where, upon clicking on a director's name from the menu, all other menu items disappear and only the selected director's biography and work are displayed. My current challenge ...

Can you explain the distinction between incorporating and excluding the keyword "await" in the following code snippets?

Currently, I'm diving into an MDN article that covers async/await. I've grasped the rationale behind using the async keyword preceding functions, yet there's a bit of uncertainty regarding the await keyword. Although I've researched "aw ...

Assertion using Node.js with Selenium WebDriver

I am currently working on implementing assertions for testing using selenium webdriver with node js. However, I am encountering an issue where it returns undefined when trying to assert the page title (which is the URL of the page). It seems like I may n ...

Tips for verifying a list of objects within a request body with JOI

I'm in the process of validating the request body for an order placement. The request body contains an array of JSON objects that I need to validate, but I keep encountering the error message "productId" is required. Below is the structure of my requ ...

Step-by-step guide on building a mat-table with nested attributes as individual rows

Here is the data structure I am working with: const families = [ { name: "Alice", children: [ { name: "Sophia" }, { name: "Liam" ...

Transmit information from node.js to the frontend utilizing only raw JavaScript

Seeking guidance on sending data object from a Node.js server to a JS file for frontend use. In the main.js file, DOM manipulation is performed. The following request is made: let dataName = []; let request = async ('http://localhost:3000/') =& ...

In order for element.click() to be successful, alert() must be called beforehand

Recently, I created a tampermokey script that keeps track of the i intervals and automatically clicks on the next video. However, it's quite strange that the script only works properly when the alert line is uncommented: var i = 1; setInterval(functi ...

Exploring the functionality of setFromSphericalCoords in Three.js

I am currently working on a Three.js application that serves as a 3D visualization of the ISS. To retrieve the latitude, longitude, and altitude of the ISS, I am utilizing this API. My challenge lies in rotating the ISS model around my Earth model. I am en ...

Implementing a specialized CSS handler for Node.JS

Currently, I have set up a Node.JS server for a new project at my workplace. As part of the project, I have created an optimizer function that removes unnecessary elements such as tabs, newlines, and comments from HTML, JavaScript, and CSS files. Strangel ...

Error: Unable to access the property 'map' as it is undefined | React, Redux

I'm encountering an issue that says: TypeError: Cannot read property 'map' of undefined. This error is related to trying to map over the array (posts) when it's empty: const postsList = posts.map((postList, i) => { Here is my actio ...

What is the reason for the lack of user data being saved in studio3t?

I'm struggling to identify the issue in my app development process. I'm creating an application that collects user email and password, storing them in a database. The problem lies in the fact that while user passwords are successfully stored, the ...

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...

Converting a single world coordinate unit into screen pixels using THREE.js

Imagine I have a unit cube and want to know how many screen pixels represent one coordinate unit when there is no scaling applied. https://i.sstatic.net/mtLjH.png Now, if I zoom in, how many screen pixels will represent this same one coordinate unit? ht ...

Creating dynamic HTML elements with bound JSON data

When a JSON array list of objects is retrieved from the database, it is sent to the client side upon page load of the current user control. var json = new JavaScriptSerializer(); var jsonList = json.Serialize(mylList); Page.Client ...

I am not sure how to properly execute this asynchronously

I have compiled a comprehensive list of everything related to this command I've been developing, and here is the error it keeps throwing at me. I tried testing if the image search feature was working properly, but instead, here's what I got: Synt ...

The error "Uncaught TypeError: Cannot read property 'render' of undefined" occurs when using Three.js along with OrbitControls

I am having an issue with my rotating cube class. Whenever I try to rotate or zoom the cube, I encounter an error message saying "Cannot read property 'render' of undefined". I suspect that the problem lies within the scopes. Below is my class im ...

The input value linked with Vue is not displaying on the DOM

I am attempting to connect a property of an item within an array in the data object of Vue to the value attribute of an input tag using binding. However, when I inspect the DOM of a web browser, it does not display. <template v-for="role in roles"> ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...