将加载的 JSON 文件与名称关联以供以后访问 [英] Associate loaded JSON files with a name for later access

查看:15
本文介绍了将加载的 JSON 文件与名称关联以供以后访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加载多个 JSON 文件并控制其网格的可见性.为了实现这一点,我将它们与它们的 JSON 文件名相关联.我让它工作了,但解决方案让我不满意.

I would like to load multiple JSON files and control the visibility of their meshes. To achieve this, I associated them with their JSON file names. I got it working, but the solutions doesn't please me.

我修改了 THREE.JSONLoader 并向回调函数传递了一个新参数.因此,对于three.js 的每个新版本,我都必须再次修补three.js 文件.

I modified the THREE.JSONLoader and passed a new parameter to the callback function. So with every new release of three.js, I would have to patch the three.js file again.

这是我的工作解决方案(客户端).见 loader.load(filename, callback, meshname) 新增的第三个参数.

Here is my working solution (client side). See the new third parameter of loader.load(filename, callback, meshname).

有没有更好的解决方案,不需要打补丁的three.js库?

Is there a better solution, which doesn't need a patched three.js library?

谢谢

// Load the JSON files
var meshes = new Object();
var jsonFileNames = ['assembly/part1.json', 'assembly/part2.json', 'assembly/part3.json'];
for(var i = 0; i < jsonFileNames.length; i++){
    var loader = new THREE.JSONLoader();
    var meshName = jsonFileNames[i].split("/")[1].split(".")[0];
    loader.load(jsonFileNames[i], function(geometry, meshName){
        mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({vertexColors: THREE.FaceColors}));
        mesh.scale.set(0.2, 0.2, 0.2);
        mesh.doubleSided = true;
        scene.add(mesh);
        meshes[meshName] = mesh;
    }, meshName);
}

// ....

// Access their meshes
meshes[meshName].visible = true;

推荐答案

您可以创建一个回调工厂,如下所示.它将解决在循环内创建时的闭包问题.

You could create a callback factory like below. It will work around the problem with closures when created inside loops.

function makeHandler(meshName) {
    return function(geometry) {
        mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({vertexColors: THREE.FaceColors}));
        mesh.scale.set(0.2, 0.2, 0.2);
        mesh.doubleSided = true;
        scene.add(mesh);
        meshes[meshName] = mesh;
    };
}

// Load the JSON files
var meshes = new Object();
var jsonFileNames = ['assembly/part1.json', 'assembly/part2.json', 'assembly/part3.json'];
for(var i = 0; i < jsonFileNames.length; i++){
    var loader = new THREE.JSONLoader();
    var meshName = jsonFileNames[i].split("/")[1].split(".")[0];
    loader.load(jsonFileNames[i], makeHandler(meshName));
}

// ....

// Access their meshes
meshes[meshName].visible = true;

这篇关于将加载的 JSON 文件与名称关联以供以后访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆