Having trouble with getting onDocumentMouseDown function in Three.js to function properly

I've been trying to implement a feature where the raycaster in onDocumentMouseDown can detect sprites when the user clicks on any part of them. However, despite borrowing from several examples, I seem to be facing alignment issues. Currently, the picking functionality is off, as clicking slightly to the right, above, or below a sprite may trigger it, while clicking directly on the left edge has no effect. There seems to be a misalignment that I can't seem to pinpoint. Any advice or guidance on this matter would be greatly appreciated.

<script src="/common/three.js"></script>
<script src="/common/Detector.js"></script>
<script src="/common/CanvasRenderer.js"></script>

<script src="/common/GeometryUtils.js"></script>
<script src="/common/OrbitControls.js"></script>

<div id="WebGLCanvas"></div>

<script>
    // Your script here
.</script>

Answer №1

If you modify your makeTextSprite() function by including the following code snippet after

var textWidth = metrics.width;

you can observe that your sprites do not have the expected size:

context.strokeStyle = "white";
context.lineWidth = 5;
context.strokeRect(0,0,canvas.width, canvas.height);

An alternative approach is to specify the canvas size as shown below:

var ctxFont = "bold " + fontsize + "px " + fontface;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = ctxFont;
var metrics = context.measureText(message);
var textWidth = metrics.width;

canvas.width = textWidth + borderThickness * 2;
canvas.height = fontsize * 1.2 + (borderThickness * 2);
context = canvas.getContext('2d');
context.font = ctxFont;

Subsequently, adjust the scale of the sprite using the following line of code:

sprite.scale.set(canvas.width / 10, canvas.height /  10, 1);

For a demonstration, refer to this jsfiddle example.

Answer №2

It's important to keep in mind that your Three.js canvas may not be positioned at the top left corner of the screen, so you need to consider the offset from 0,0 on the page. To resolve this issue, adjust the mouse position by subtracting the offset.

var containerRect = container.getBoundingClientRect();
mousePosition.x = ((event.clientX - containerRect.left) / renderer.domElement.clientWidth) * 2 - 1;
mousePosition.y = -((event.clientY - containerRect.top) / renderer.domElement.clientHeight) * 2 + 1;

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

The magnitude of each new keystroke is squared compared to its predecessor

exploring the relationship between keyboard and console inputs Each subsequent e.key entry is occurring twice as frequently as the previous one. Once it reaches 8-9 characters, the rendering frequency skyrockets to over 1000 times per character. Here&apos ...

"Encountering an error retrieving weather forecast API in JavaScript - issue with

I've been attempting to fetch the weather forecast API JSON in a similar manner to how I accessed the current weather API, but unfortunately, it doesn't seem to be working no matter what approach I take. let inOneDay = { fetchWeather: functio ...

Error encountered during login with Facebook on Cordova: "Unable to create module facebookApp because of..."

As a novice programmer, I am attempting to incorporate Facebook login using Cordova. Following a recent guide provided here, I have meticulously copied and pasted the code into a new Cordova project. While I am familiar with jQuery, this is my first encoun ...

Choose an image for a better view with the use of HTML and JavaScript/JQuery

Requesting assistance in creating a simple code using plain html5 and JavaScript/jQuery (without plugins) that will enlarge an image upon clicking on it from a list of images. Here is the HTML snippet provided: <!-- Large image holder --> & ...

Utilizing Electron API within an Angular Component

I'm hoping to utilize a locally stored video file in electron and play it within my angular component. Despite exposing the loadLocalFile function to prevent the need for setting nodeIntegration to true, I keep receiving a Security Warning : This re ...

Converting URL for AJAX POST information

While trying to encode a URL using encodeURIComponent, I encountered a 500 SERVER ERROR on certain URLs. It appears that the issue lies in the encoding process, as removing the data resolves the error entirely. What is the correct way to encode the URL to ...

JavaScript threw an error because it encountered an unexpected or invalid token

I can't seem to identify the error in this code. Can someone please help me correct it? document.write(' <div> <a href=http://www.socialsignal.ir style=\'\\padding:5px;text-decoration: none;border: 1px solid #555;ba ...

The issue with CSS and JavaScript is causing the appended elements to not display properly in PHP code

I am currently facing issues with retrieving the grandchildren from my database table named referrals. Surprisingly, my code successfully retrieves the username of my grandchildren, but it does not display below the line of my child and there are no errors ...

What is the process for integrating an autoplay script into Turn.Js?

Can someone guide me on how to implement this code in Turn.Js? setInterval(function() { $('#flipbook').turn('next'); }, 1000); ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

Determining the completion of loading in Android WebView

I am seeking to understand how to accurately determine when a WebView has finished loading in its entirety. To clarify what is meant by "completely": All redirects have been processed The entire page is visibly displayed, with no additional elements lef ...

What is the best way to transmit the attributes of an object with a defined state in one React component to another component using a link and display them?

I currently have two components and one route in my project. I am trying to pass the properties of the place object from one component to another so that I can display them accordingly. The first component holds the list of places in its state, where I map ...

Draggable HighStock element causing issues with Gridster dragging

I have integrated a stocks chart from HighStocks with gridster, where each gridster block is draggable. However, the stocks time slider gadget can also be dragged and resized. When I move the slider on top of a gridster widget, the entire widget moves alon ...

Having difficulty in displaying database values in HTML modal using PHP

On my PHP page, I have a setup that displays data based on the fetched id from the URL. Everything is working smoothly, but when I click a button to show a modal with additional information, the modal appears blank. Here is the code snippet I am using: ...

Ways to Retrieve the Value of an Object

Here is some sample data: { "id": 1, "title": "Title one", "category_data": { "2": "Team", "7": "Queries" } }, A function is used to remove duplicate categories from the data: remove_category_duplicates: function () ...

What is the best way to iterate through and hide these images when they are clicked on?

I need help creating a grid of images inside divs that function like checkboxes. When you click on an image, it should disappear, and clicking again should make it reappear. I have some code that works for one image, but I can't figure out how to loop ...

Restricting the quantity of dynamic list items within a function

My current goal with the Code I'm working on involves achieving two specific outcomes, which has me debating whether to separate the questions: JS: function listPosts(data) { postlimit = var output='<ul data-role="listview" data-fil ...

Validating forms with dynamically populated fields using Jquery

Having trouble with Jquery Validation on dynamically populated fields. In my asp.net project, I need the name fields to remain constant because I split an array of information on the server side and update a database. <form id="insert_additions" action ...