简体   繁体   English

如何在 THREE.js 中加载本地图像?

[英]How can I load a local image in THREE.js?

I am trying to put an image on an object, like this:我正在尝试将图像放在对象上,如下所示:

var texture = new THREE.TextureLoader().load( 'crate.gif' );
var geometry = new THREE.BoxBufferGeometry( 200, 200, 200 );
var material = new THREE.MeshBasicMaterial( { map: texture } );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

I have "crate.gif" in my local folder, but it does not appear on the box.我的本地文件夹中有“crate.gif”,但它没有出现在盒子上。

I am expected to either run a web server, or I can use a data url, because local image loading does not work, as re-iterated by the developer.我应该运行 Web 服务器,或者我可以使用数据 url,因为本地图像加载不起作用,正如开发人员重新迭代的那样。

  • Running a web server is an unacceptable work-around and will not be considered.运行 Web 服务器是一种不可接受的变通方法,不会被考虑。
  • I may be willing to do the chore of converting every single image into Base64, but I don't know how to integrate that solution.我可能愿意做将每个图像转换为 Base64 的繁琐工作,但我不知道如何集成该解决方案。

I realize the image may not be displaying because it hasn't loaded before being called.我意识到图像可能没有显示,因为它在被调用之前没有加载。 What is the easiest way to load an image?加载图像的最简单方法是什么?

Another way to load an image as a texture is with a require and using a relative path of your image:将图像加载为纹理的另一种方法是使用 require 并使用图像的相对路径:

I'm using React and works for me.我正在使用 React 并且对我有用。

const textureImage = require('../assets/images/image.png');
const texture = new THREE.TextureLoader().load(textureImage);
const geometry = geometry = new THREE.BoxBufferGeometry( 200, 200, 200 );
const material = new THREE.MeshBasicMaterial( { map: texture } );
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

It is just as easy as using a Data URI in place of an image filename, if it's done right :很容易在地方的图像文件名的使用数据URI,如果它做的权利

var geometry = new THREE.SphereGeometry(0.5, 32, 32);
var texture = new THREE.TextureLoader().load( "data:image/jpeg;base64,/9j/4AAQSkZJRgA--(truncated-for-example)--BAgEASABIAAD" );
var material = new THREE.MeshBasicMaterial( { map: texture } );
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM