Textures have been added by the user in the three.js platform

Click here to access the jsFiddle adaptation of this problem.

In my quest to develop a cutting-edge 3D web application, I aim to allow users to choose an image file from their device:

<input id="userImage" type="file"/>

Once a file is selected, the image becomes a key parameter in a THREE.ShaderMaterial object. A glsl shader is then applied to the image and the outcome is displayed within a browser container:

$("#userImage").change(function(){
    var texture = THREE.ImageUtils.loadTexture( $("#userImage").val() );
    texture.image.crossOrigin = "anonymous";
    shader.uniforms.input.value = texture;
    shader.uniforms.input.needsUpdate = true;
});

Sadly, an error arises during this process:

Cross-origin image load denied by Cross-Origin Resource Sharing policy.

I am aware of the challenges related to fetching cross-origin resources in WebGL. However, the official WebGL specification offers a potential solution:

The following ECMAScript example demonstrates how to issue a CORS request for an image coming from another domain. The image is fetched from the server without any credentials, i.e., cookies.

var gl = ...;
var image = new Image();

// The onload handler should be set to a function which uploads the HTMLImageElement
// using texImage2D or texSubImage2D.
image.onload = ...;

image.crossOrigin = "anonymous";

image.src = "http://other-domain.com/image.jpg";

Although I have set the crossOrigin value for the image as specified, the error persists. What distinguishes my approach from the documented example? Can local resources be utilized in WebGL similar to external server-hosted resources? Alternatively, are there alternative solutions I should explore to achieve my objective?

Answer №1

This solution is commonly used for previewing local images before uploading them to a server. By converting the image to a data URL, it bypasses cross-origin policies. You can find the corrected code here. Here's the main part of it:

userImage = $("#userImage")[0];
if (userImage.files && userImage.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        image.src = e.target.result;
    };

    reader.readAsDataURL(userImage.files[0]);
}

Answer №2

Encountering a similar issue, I found myself with code that closely resembled the following:

var map = THREE.ImageUtils.loadTexture( e.target.result );

To resolve the issue, I had to make the following adjustments:

var image = document.createElement( 'img' );
var texture = new THREE.Texture( image );
image.onload = function()  {
    texture.needsUpdate = true;
};

Implementing these changes effectively resolved the problem.

Answer №3

Here is a solution with an illustrative example: The libraries used in this solution are: - modal - jcrop - html5canvas Best regards.

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

Generate a key pair using the cryto library and then use it with the json

There's a new method called generateKeyPair in node 10, and I am utilizing it in the following way: const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 4096, publicKeyEncoding: { type: "spki", format: "pem ...

The second node child process encounters execution issues in Linux

For a challenge, I needed to find a way to automatically restart my bot within itself. After some trial and error, I came up with a solution. However, when testing on a Raspberry Pi via ssh, the process exits after the first child process ends. Surprisingl ...

Is it important to minify JavaScript npm packages?

In my journey of creating numerous npm packages, I find myself pondering over the question: "Should JavaScript npm packages be minified?" I have always held the belief that minifying already minified code is not a good practice, which is why I have refrai ...

Why is the jQuery not functioning within the AngularJS function?

I am encountering an issue with writing jQuery inside an AngularJS function. I can't seem to figure out why it's not working properly. HTML <div> <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showD ...

Managing checkbox behavior using ajax

Currently, I am utilizing a CSS toggle button to display either active or inactive status. This toggle button is achieved by using an HTML checkbox and styling it with CSS to resemble a slide bar toggle. The assigned functionality involves binding the onCl ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

Activate Angular Material's autocomplete feature once the user has entered three characters

My goal is to implement an Angular Material Autocomplete feature that only triggers after the user has inputted at least three characters. Currently, I have it set up so that every click in the input field prompts an API call and fetches all the data, whic ...

Prevent a function from executing using ClearTimeout()

Looking for a way to control the progress of my progress bar using two buttons. Here's the code snippet: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0 /jquery.min.js"></scr ...

What is the best way to export assets into a React Native JS file?

After watching a video on YouTube, I noticed that at 3:20 the individual in the video quickly exported multiple assets into a file without providing any explanation. Can someone please view this specific moment in the video and clarify how this person mana ...

Can a file object be transmitted using this method?

I'm new to jquery and I am attempting to upload a File object obtained from my HTML: <label for="photo" class="col-xs-2">Photo</label> <input id="photo" name="fileName" type="file" class="col-xs-4"/> This is the snippet of my J ...

Vue.js - The table updates successfully, however, the data for the selected checkboxes remains unchanged

Encountered a persistent bug that is giving me some trouble. I have a table with rows that can be selected, and when a checkbox is checked, the total amount in the column should be calculated. However, whenever there is a change in the table data through ...

Ways to automatically update ng-class based on changes in ng-model value

I am working on a code where I need to add classes to the 'label' based on whether the input box is empty or not. To achieve this, I am checking if the input box is null and adding classes accordingly. <div class="col-md-12"> <input ...

Is it possible to execute an ajax function at regular intervals until a specific condition is fulfilled?

My application consists of two JSP pages. One is responsible for the UI, while the other processes the response. UICounter.jsp: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Page</titl ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

Creating input fields dynamically within Yii2 framework

I'm currently facing a challenge with forms in Yii2. My objective is to design a form that includes three dropdown menus, inquiring about the user's preferred time(s) during the week. The first menu will focus on selecting days of the week, while ...

Can't I prevent additional renders using useMemo()?

I am facing an issue with my function-based component that fetches data using redux toolkit and useAppSelector(). I have placed a console.log within the component to monitor its behavior. However, upon refreshing the page, the console.log continues to appe ...

Manage shared nested modules across different modules in Vuex without redundancy

In my Vue.js application, I am using Vuex as the state manager. To ensure that certain states are shared across different components, I have created a nested state containing all the common information. This allows me to import it into multiple modules. F ...

Error: Tried to modify a property that is read-only while using the useRef() hook in React Native with Typescript

https://i.sstatic.net/jhhAN.pngI'm facing an issue while attempting to utilize a useRef hook for a scrollview and pan gesture handler to share a common ref. Upon initializing the useRef() hook and passing it to both components, I encounter an error th ...

The web page's content remains hidden until it is scrolled into view, despite the fact that the page has finished loading

I'm a beginner with Angular and currently working on creating a website. On the following page , when viewed on mobile, I am experiencing an issue where the content doesn't load until it's brought into view by scrolling down the page. I am u ...