Three.js + OrbitControls - 未捕获的类型错误:无法读取未定义的属性“渲染" [英] Three.js + OrbitControls - Uncaught TypeError: Cannot read property 'render' of undefined
问题描述
我正在编写一个用于旋转立方体的类,但每次旋转或缩放时,都会收到错误消息无法读取未定义的‘渲染’属性".我究竟做错了什么?我想范围有问题.这是我的课:
I am writing a class for rotating cube, but every time i rotate it or zoom, i get an error "Cannot read property 'render' of undefined". What am i doing wrong? I guess something is wrong with the scopes. Here is my class:
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);
};
};
坦克.
推荐答案
您在此处指定的回调中存在范围问题:
You have a scoping problem in the callback specified here:
this.controls.addEventListener( 'change', this.render );
在您的班级中,添加
var scope = this;
然后像这样重写你的 render()
方法:
Then rewrite your render()
method like so:
this.render = function () {
scope.renderer.render( scope.scene, scope.camera );
};
另外,添加事件监听器的目的是去除动画循环.
Also, the point of adding the event listener is to remove the animation loop.
所以...,删除它,并且仅在鼠标导致相机移动时进行渲染.
So..., remove it, and only render when the mouse causes the camera to move.
您还必须在最初和模型加载后调用一次 render()
.
You will also have to call render()
once initially, and after models load.
three.js r.69
three.js r.69
这篇关于Three.js + OrbitControls - 未捕获的类型错误:无法读取未定义的属性“渲染"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!