javascript - 无法在Three.js中加载本地纹理,并在vue.js中将三个作为组件运行

我在vue中将Three.js动画作为组件运行。当我将纹理作为外部联机资源加载时,它工作正常,但是当我尝试在本地运行纹理时,它显示为黑色,没有错误消息。

  this.myTexture = new THREE.TextureLoader().load(
    "https://vuejs.org/images/logo.png"
    // This doesnt work - why?
    // "../assets/logo.png"
  );
我在浏览器中使用插件允许cors,因此与cors问题无关...
运行本地vue服务器时如何运行它?
这是github上的完整仓库:
https://github.com/reppoper/vuethreetexture
我的代码:
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 doesnt 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>

最佳答案

It works fine when I am loading the texture as an external onlineresource


由于浏览器的CORS政策,这对我不起作用。 Chrome浏览器控制台说:

Access to 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.


尝试使用以下代码:
this.myTexture = new THREE.TextureLoader().load(
    require( "../assets/logo.png" )
);

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