Having trouble loading a local texture in Three.js while using it as a component in Vue.js

When I run a three.js animation as a component within Vue, it works perfectly fine when loading the texture from an external online resource. However, when I try to run it locally by loading the texture from a local path, it displays black with no error messages.

  this.myTexture = new THREE.TextureLoader().load(
    "https://vuejs.org/images/logo.png"
    // This doesn't work - why?
    // "../assets/logo.png"
  );

I am using a browser addon to allow CORS, so it is not related to CORS problems...

How can I get it to run when I am running my local Vue server?

Here is the full repository on GitHub: https://github.com/reppoper/vuethreetexture

My code: App.vue

<template>
  <div id="app">
    <HelloThreeBasic/>
  </div>
</template>

<script>
import HelloThreeBasic from './components/HelloThreeBasic.vue'

export default {
  name: 'App',
  components: {
    HelloThreeBasic
  }
}
</script>

HelloThreeBasic.vue

<template>
  <div>
    <div id="container"></div>
  </div>
</template>
<script>
import * as THREE from "three";

export default {
  name: "HelloThree",
  data() {
    return {
      cube: null,
      renderer: null,
      scene: null,
      camera: null,
      container: null,
      myTexture: null,
    };
  },
  methods: {
    init: function () {
      this.scene = new THREE.Scene();
      this.camera = new THREE.PerspectiveCamera(75,window.innerWidth / window.innerHeight,0.1,1000);
      this.renderer = new THREE.WebGLRenderer();
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.container = document.getElementById("container");
      this.container.appendChild(this.renderer.domElement);

      const geometry = new THREE.BoxGeometry(1, 1, 1);
      this.myTexture = new THREE.TextureLoader().load(
        "https://vuejs.org/images/logo.png"
        // This doesn't work - why?
        // "../assets/logo.png"
      );

      const material = new THREE.MeshBasicMaterial({
        color: 0xffffff,
        map: this.myTexture,
        transparent: false,
      });
      this.cube = new THREE.Mesh(geometry, material);
      this.scene.add(this.cube);
      this.camera.position.z = 2;
    },
    animate: function () {
      requestAnimationFrame(this.animate);
      this.cube.rotation.x += 0.01;
      this.renderer.render(this.scene, this.camera);
    },
  },
  mounted() {
    this.init();
    this.animate();
  },
  beforeDestroy() {
    delete this.container;
  },
};
</script>

<style >
#container {
  width: 100%;
  height: 100%;
  top: 0;
  position: absolute;
  z-index: -10;
}
</style>

Answer №1

When I load the texture as an external online resource, everything works smoothly.

Unfortunately, this approach doesn't work for me due to the browser's CORS policy. Chrome's browser console displays the following error message:

Access to the image at 'https://vuejs.org/images/logo.png' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Instead, you can try using the following code:

this.myTexture = new THREE.TextureLoader().load(
    require( "../assets/logo.png" )
);

const material = new THREE.MeshBasicMaterial({
    map: this.myTexture,
    alphaTest: 0.5
});

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

Sequential execution not functioning properly in NodeJS Async series

Here is the code snippet I am working with: var async = require('async'); var rest = require('restler'); async.series([ function(callback){ rest.get('https://api.twitter.com/1.1/statuses/mentions_timeli ...

Is it possible to have the front-facing photo in expo-camera stay mirrored?

Currently, I am utilizing the expo-camera library to capture a selfie image. Despite the preview being mirrored, the final saved image reverts to its normal orientation. Is there any way to avoid this behavior so that the image remains mirrored? Alternativ ...

Connecting node.js to a MySQL database on a WAMP/XAMPP server: A step-by-step guide

As a PHP programmer, I am experienced with WP, CI, and OC. However, I am a complete beginner when it comes to node.js and how to connect MySql with WAMP/XAMPP in a step-by-step method. If I were to set up a live server for this project, what would be the ...

Getting the ID of a button: A step-by-step guide

My query involves a file named Index.aspx connected to another file called seatbooks.js. Within Index.aspx, there is a button with the id Indexbutton. This button has an eventonclick='book_ticket()' attribute. The book_ticket() method is includ ...

Modifying the property value in a child component using the parent component in VueJS

Hey there, I'm facing an issue where I need to update a prop in my child component when the parent component changes the value. However, I'm attempting to do this in a unique way and running into a problem where the child prop is not being update ...

javascript code not functioning properly

Something simple! In my asp.net-MVC project, I have a button and an external JavaScript file called mydata.js. This file contains a function called checkJS(). function checkJs() { debugger; alert("your output!!!"); } Here is my code: <div id="m ...

Creating a new row in a Tabulator component in React and retrieving the data

I have incorporated the react-tabulator library into my project and I am looking for guidance on how to dynamically add new rows once the tabulator has been rendered. Ideally, I would like to include a button below the tabulator that enables users to add a ...

How can I make a Vue component close when clicking outside of it?

I am searching for a solution to automatically close a component when there is a click outside of the element. I attempted to use an addEventListener for this purpose. Although it successfully closes the component, it encounters an issue where it fails to ...

Utilizing SSAO in AFrame with Three.js Pass

I've successfully integrated the Threejs Effect composer into AFrame as a component by exporting everything as THREE.EffectComposer, THREE.SSAOPass, etc. and adding the effect inside an AFrame component. I had to tweak the AFrame renderer to update th ...

Unexpected Error: The axiosCookieJarSupport function is throwing a TypeError, functioning properly in Node.JS but not in .vue pages. What could

Struggling with a function that authenticates on a website, it runs smoothly in a basic node.js script but fails when executed from a .vue page within the NuxtJS framework. The error message received when running in the .vue page is TypeError: axiosCookie ...

Slow auto page refresh in local development for Angular2 on Windows can be quite frustrating

Recently diving into angular2 and following the heros tutorial from docs. Struggling with a sluggish development experience while working with angular2. It's taking approximately 5 seconds for angular2 to recognize changes in files, followed by anothe ...

Locate an element within an array of strings to refine the contents of a flatlist

Currently, I have a FlatList that I am attempting to filter using multiple inputs from dropdown selectors. Here is the code snippet for my FlatList component: <FlatList style={styles.list} data={data.filter(filteredUsers)} ...

Object Illumination Effect Using Three.js

Currently, I am working on creating an earth scene using Three.js and everything seems to be going well except for the large and distracting reflection disc that appears on the surface of the earth object. Does anyone have any suggestions on how to either ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Leveraging HTTP/2 in conjunction with angularJS

As I was exploring ways to improve the performance of my web application, I came across HTTP/2. After learning about its features that can enhance website speed, I decided to implement it. Upon upgrading my browser to the latest version to enable HTTP/2 s ...

Input boxes next to each other in a Vuetify form

Is it possible to place multiple input controls next to each other using v-form? Thanks This is my code, I want to have the text edits side by side (2 on each line) <v-form ref="form" v-model="valid"> <v-select :items ...

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Preparing the format/serialization of a JQuery JSON array prior to submitting it

Looking at the JSON structure I have: { "firstArrayOfJSON": [ { "something" : "something" }, { "another" : "another" }, { "secondArrayOfJson" : [ ...

Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original. Check out my code below: window.onload = function() { ImageObjSketch = new Image(); // URL ImageObjSketch.src = 'https://i.imgur.com/75lATF9 ...

Finding the Number of Days Between Two Dates in AngularJS Using JavaScript

When I receive two dates from a web service in the format below: var dateone = "2016-08-21T07:00:00.000Z"; var datetwo = "2016-08-28T07:00:00.000Z"; var datediff = datetwo - dateone; var numdays = Math.round(datediff); console.log("Number of Days is " + n ...