我正在为旋转立方体写一个类,但每次我旋转或缩放时,都会出现错误"无法读取属性'渲染'未定义"。我究竟做错了什么?我猜这些范围有问题。这是我的班级:
myclass = function() {
this.camera = null;
this.scene = null;
this.renderer = null;
this.product = null;
this.init = function (container) {
this.scene = new THREE.Scene();
this.camera = createCamera();
this.product = createProduct();
this.scene.add(this.product);
this.createRenderer();
this.setControls();
container.appendChild(this.renderer.domElement);
this.animate();
};
function createCamera() {
var camera = new THREE.PerspectiveCamera(20, 300 / 400, 1, 10000);
camera.position.z = 1800;
return camera;
}
function createProduct() {
var geometry = new THREE.BoxGeometry(300, 200, 200);
var materials = ...;
var product = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
return product;
}
this.createRenderer = function () {
this.renderer = new THREE.WebGLRenderer({antialias: true});
this.renderer.setClearColor(0xffffff);
this.renderer.setSize(this.sceneWidth, this.sceneHeight);
};
this.setControls = function () {
this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
this.controls.addEventListener('change', this.render);
};
this.animate = function () {
requestAnimationFrame(this.animate.bind(this));
this.render();
};
this.render = function () {
this.renderer.render(this.scene, this.camera);
};
};
Tnanks。
答案 0 :(得分:3)
您在此处指定的回调中存在范围问题:
this.controls.addEventListener( 'change', this.render );
在班上,添加
var scope = this;
然后重写您的render()
方法:
this.render = function () {
scope.renderer.render( scope.scene, scope.camera );
};
此外,添加事件侦听器的目的是删除动画循环。
所以...,删除它,只有在鼠标导致相机移动时才会渲染。
您最初必须先调用render()
,并在模型加载后调用。
three.js r.69
答案 1 :(得分:0)
您可以按以下方式使用bind方法,它将保留render方法的作用域
this.controls.addEventListener( 'change', this.render.bind(this) );