【问题标题】:Loading textures in Three.js with XHR progress events使用 XHR 进度事件在 Three.js 中加载纹理
【发布时间】:2017-04-18 21:47:17
【问题描述】:

Three.js (R84) 的当前版本使用图像标签加载纹理,不支持 onProgress 事件。我可以推断已加载了多少文件,但无法公开有关已加载字节的详细信息。

加载带有 onProgress 事件支持的纹理的最佳方式是什么?我想支持各种移动客户端,但不关心旧版桌面支持。

【问题讨论】:

标签: three.js


【解决方案1】:

一种解决方案是先通过 FileLoader 加载文件,然后使用 TextureLoader 从缓存中加载。内存缓存意味着文件只加载一次,即使它没有从服务器获取缓存头。

结果是我们通过 FileLoader 的初始 AJAX 获取获取进度事件,但仍然可以利用正确 TextureLoader 的所有有用行为(例如禁用 JPEG 纹理的 Alpha 通道和其他优化)。

/**
 * Loads THREE Textures with progress events
 * @augments THREE.TextureLoader
 */
function AjaxTextureLoader() {
    /**
     * Three's texture loader doesn't support onProgress events, because it uses image tags under the hood.
     *
     * A relatively simple workaround is to AJAX the file into the cache with a FileLoader, create an image from the Blob,
     * then extract that into a texture with a separate TextureLoader call.
     *
     * The cache is in memory, so this will work even if the server doesn't return a cache-control header.
     */

    const cache = THREE.Cache;

    // Turn on shared caching for FileLoader, ImageLoader and TextureLoader
    cache.enabled = true;

    const textureLoader = new THREE.TextureLoader();
    const fileLoader = new THREE.FileLoader();
    fileLoader.setResponseType('blob');

    function load(url, onLoad, onProgress, onError) {
        fileLoader.load(url, cacheImage, onProgress, onError);

        /**
         * The cache is currently storing a Blob, but we need to cast it to an Image
         * or else it won't work as a texture. TextureLoader won't do this automatically.
         */
        function cacheImage(blob) {
            // ObjectURLs should be released as soon as is safe, to free memory
            const objUrl = URL.createObjectURL(blob);
            const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');

            image.onload = ()=> {
                cache.add(url, image);
                URL.revokeObjectURL(objUrl);
                document.body.removeChild(image);
                loadImageAsTexture();
            };

            image.src = objUrl;
            image.style.visibility = 'hidden';
            document.body.appendChild(image);
        }

        function loadImageAsTexture() {
            textureLoader.load(url, onLoad, ()=> {}, onError);
        }
    }

    return Object.assign({}, textureLoader, {load});
}

module.exports = AjaxTextureLoader;

【讨论】:

  • 很不错的解决方案!
猜你喜欢
  • 2017-06-05
  • 2013-06-28
  • 2023-04-09
  • 2015-05-30
  • 2015-08-04
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多