Converting 2D pixel art into 3D coordinates with ThreeJS

Attempting to display a cube generated in ThreeJS on an HTML canvas at a specific location has been quite challenging.

The location is defined in pixels, for example (100,200). Unfortunately, the process of converting these pixel values into ThreeJS coordinates remains elusive.

// Dimensions of my canvas are 640 X 480
const CANVAS_WIDTH = 640;
const CANVAS_HEIGHT = 480;

// Create a cube and add it to the scene
let geometry = new THREE.CubeGeometry(1, 1, 1);
let materials = createMaterials();
this.cube = new THREE.Mesh(geometry, materials);
this.cube.doubleSided = true;
this.scene.add(this.cube);

// Set up the camera
this.camera = new THREE.PerspectiveCamera(45, CANVAS_WIDTH / CANVAS_HEIGHT, 1, 5000);
this.camera.position.z = CANVAS_WIDTH / 2;
this.scene.add(this.camera);

An interesting discovery was made that the origin (0,0) in ThreeJS corresponds to the center of the screen.

If anyone has insights on how to translate 2D coordinates from the canvas into 3D coordinates compatible with ThreeJS, kindly share your knowledge. Any assistance would be greatly appreciated.

Answer №1

Here's a method you can consider, utilizing the THREE.Raycaster():

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 box = new THREE.Mesh(new THREE.BoxBufferGeometry(), new THREE.MeshBasicMaterial({
  color: "red",
  wireframe: true
}));
scene.add(box);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();

document.addEventListener("mousedown", onMouseDown);

function onMouseDown(event) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  raycaster.setFromCamera(mouse, camera);

  var dist = box.position.clone().sub(camera.position).length();

  raycaster.ray.at(dist, box.position);

}


renderer.setAnimationLoop(() => {
  renderer.render(scene, camera);
});
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>

Another approach is to utilize a raycaster and THREE.Plane(), determining the intersection point of the raycaster's ray with the plane.

Answer №2

Initially, when working with a three.js scene, it's important to remember that it renders in 3D, meaning that your object's position should have coordinates in all three dimensions (X, Y, Z) within the scene. To adjust the position of your object, you can use the following code:

Object.position.set( x , y , z );
. The z position specifically determines how close or far the object is from the camera. Best of luck! Remember to set the z value to 0 if you want to place your object at specific coordinates (x, y, 0).

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

Tips for releasing a dual npm package with both CommonJS and module support to ensure consistent imports of submodules

Trying to figure out how to package an NPM package so that it includes both CommonJS and ES modules that can be imported using the same absolute module path has been a challenge for me. I want to ensure that regardless of whether it's in a node or bro ...

Exploring elements within a JavaScript array

I'm struggling to retrieve model objects from my view model. It seems like a JavaScript/KnockoutJS familiarity issue, so any guidance is welcomed. Here is the code snippet: <!-- VIEW --> <select data-bind="options: allTypes, ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

Learn how to send information to a form and receive a response when a key is pressed, either up or down, by

Can you help with fetching data and passing it into a form to respond to customer names on keyup or keydown using JSON and PHP? <?php $conn = new mysqli("localhost", 'root', "", "laravel"); $query = mysqli_query($conn,"select * from customers ...

Using Typescript, Angular, and Rxjs to retrieve multiple HttpClients

I am looking to send get requests to multiple endpoints simultaneously, but I want to collect all the responses at once. Currently, this is how a single endpoint request is handled: public getTasks(): Observable<any> { this.logger.info('Ta ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Trouble resolving a timer interruption in JavaScript

Creating dynamic elements using PHP has brought me to a new challenge. I want to implement a functionality where the user can hover over an icon and see the related element, which should disappear after some time if the mouse leaves the icon. Additionally, ...

Issues occurred when attempting to access information with postgres and nodeJS

Below is the configuration I have set up in my files: const express = require('express') const app = express() const port = 8000 const expense_model = require('./expense_model') app.use(express.json()); app.us ...

Passing state to getStaticProps in Next JSLearn how to effectively pass state

I am currently fetching games from IGDB database using getStaticProps and it's all working perfectly. However, I now have a new requirement to implement game searching functionality using a text input field and a button. The challenge I'm facing ...

Exploring the world of design with React JS and MUI's diverse styling options

Exploring the various styling options offered by MUI From useTheme, styled, makeStyles to other methods - what sets them apart and how do they differ in use cases? We're looking for a comprehensive breakdown of their unique features, practical appli ...

Always display all options in MUI Autocomplete without any filtering

I am seeking to eliminate any filtering in the MUI Autocomplete component. My goal is for the text field popper to display all available options. The results are obtained from a server-side search engine. These results, or "hits," already provide a filter ...

Unable to locate the element within a component using Cypress

I need help locating the dropdown arrow. I tried using the Cypress command cy.get('.dropdown-arrow').click() but it's throwing an error saying element not found. Below is the code snippet: <widgets-bms-scoreboard> <div class=&q ...

I am in the process of transforming my basic JS Array into one that contains key/value

Currently, I am utilizing jQuery to create an Array in the following manner: var arr = new Array(); $('#some-form .some-input').each(function() { arr.push($(this).val()); ...

dart, setting the root directory for web application

I'm looking to include some sample websites in my web framework package. Currently, the sites work fine when running them as Dart-only implementations, but if I need to compile them to JavaScript, I have to manually move the subfolder from my package& ...

Ways to resolve - Error: Unable to access 'comments' property of null

I am currently working on developing a blog web application and I am facing an issue with enabling user comments on posts. Despite extensive research and attempts to troubleshoot by searching online, I have not been able to find a solution. I have been str ...

The architecture of Angular controllers

Being a novice in AngularJs, I have a query regarding the controller structure. This particular file is my employeeController.js (function() { angular.module('employeeApp').controller('employeeController', employeeCont ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

In Angular, when a promise returns an "undefined" value, how does this interact with .NET

When I execute this code snippet, I am encountering an issue where the response returned is "undefined" instead of the expected value. Here is the code in question: $scope.SameNameFunction = function() { var payload = { itemname: $scope.EventD ...

Accessing S3 bucket contents in Angular using Observables

Looking for guidance on structuring a service method in Angular4 to create an s3.listObjects call and return the contents of an S3 bucket as an Observable. Here is my current attempt, unfortunately not yielding successful results: public retrieveFilesFro ...