如何在three.js中加载指定文件内容而非路径的三维模型

How to load 3-D models specifying file content rather than path in three.js?

本文关键字:路径 模型 三维 文件 three js 加载      更新时间:2023-09-26

我想创建一个在线查看器,用户可以在其中上传模型并查看它们,而不必编辑源代码中的路径。由于浏览器不允许检索文件路径,但我可以读取文件的内容,在给定文件内容的情况下,我如何加载模型(obj、ply、mtl等)?

有几种方法可以做到这一点,但如果您转到github three.js存储库,在示例中您会看到一个obj加载程序。有mtl、stl、collada等的例子。

http://threejs.org/examples/webgl_loader_obj.html

存储库有一个examples文件夹,其中有一个js文件夹,里面有所有的exampleloader:

https://github.com/mrdoob/three.js/tree/master/examples/js/loaders

如果您想颠覆内部的三个加载器,每个加载器示例都有一个parse(text)方法。

我们刚刚发现three.js在线编辑器可以做到这一点@http://threejs.org/editor/。

文件->导入。

您可以使用HTML5文件阅读器API,然后您可以直接从相应的加载器调用parse方法并得到结果。

或者,您可以使用文件读取器,将文件读取到数据url中,然后加载数据url,而不是普通url。

允许用户加载模型文件的HTML代码

<h1>Model File Reader</h1>
<div>
  Select a model file: 
  <input type="file" id="fileInput">
</div>

处理onload事件的Javascript代码:

window.onload = function() {
    var fileInput = document.getElementById('fileInput');
    fileInput.addEventListener('change', function(e) {
      // file selection is done you can now read the file
      var file = this.files[0];
      // set your file encoding
      var encoding = 'ISO-8859-1'; 
      // create a file reader
      var reader = new FileReader();
      // set on load handler for reader
      reader.onload = function(e) {
          var result = reader.result;
          // parse using your corresponding loader
          loader.parse( result );
      }
      // read the file as text using the reader
      reader.readAsText(file, encoding);
    });
}

查看此处了解有关文件读取器类的更多信息