THRE.JS动态创建对象

THREE.JS Creating an object dynamically

本文关键字:创建对象 动态 JS THRE      更新时间:2023-09-26

我有JSON配置,比如:

{ shape:[ 'SphereGeometry', [7, 16, 16] ] }

并尝试加载类似的模型:

new THREE[shape[0]].apply( this, shape[1] )

正如你所看到的,"new"answers"apply"在这里不是一个选项。有人知道我如何在这里解决问题的诀窍吗?

提前谢谢。

该解决方案基于使用带有';新';操作人员这可能吗?

JSON配置

{ shape: 'SphereGeometry', properties: [ null, 7, 16, 16 ] }

并创建一个新对象:

new (Function.prototype.bind.apply( THREE[object.shape], object.properties ))

通常将.apply()和new一起使用不是一个很好的过程,但它的过程如下:

function dynamicShape() {
    return THREE[shape[0]].apply(this, shape[1]);
}
dynamicShape.prototype = THREE[shape[0]].prototype;
var sphere = new dynamicShape();

这应该行得通。下面是一个使用一些示例代码进行渲染的fiddle:http://jsfiddle.net/jcc6zbtn/

这里有一种方法,使用reviver函数。其优点是解析过程直接负责实例化正确的对象类型,而不是分两步进行。

var shapes = { 'Rectangle': Rectangle }, //same as THREE in your code
    shapeJson = '{ "shape": ["Rectangle", [2, 4]] }',
    shape = shapeFromJson(shapeJson);
console.log(shape);
function instanciate(ctor, args) {
    var instance = Object.create(ctor.prototype);
    ctor.apply(instance, args);
    return instance;
}
function createShape(shape, args) {
    return instanciate(shapes[shape], args);
}
function shapeFromJson(json) {
    return JSON.parse(json, function (key, val) {
        return key? val : createShape(val.shape[0], val.shape[1]);
    });
}
function Rectangle(height, width) {
    this.height = height;
    this.width = width;
}