【问题标题】:Three.js + OrbitControls - Uncaught TypeError: Cannot read property 'render' of undefinedThree.js + OrbitControls - 未捕获的类型错误:无法读取未定义的属性“渲染”
【发布时间】:2020-09-22 22:18:21
【问题描述】:

我正在编写一个用于旋转立方体的类,但每次旋转或缩放时,我都会收到错误消息“无法读取未定义的属性‘渲染’”。我究竟做错了什么?我猜范围有问题。这是我的课:

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);
    };
 };

坦克。

【问题讨论】:

    标签: javascript three.js


    【解决方案1】:

    您在此处指定的回调中存在范围问题:

    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

    【讨论】:

      【解决方案2】:

      您可以按如下方式使用绑定方法,它将保留渲染方法的范围

      this.controls.addEventListener( 'change', this.render.bind(this) );
      

      【讨论】:

        猜你喜欢
        • 2020-11-26
        • 1970-01-01
        • 2012-10-01
        • 2014-01-28
        • 1970-01-01
        • 2021-12-22
        • 2015-01-06
        • 2017-07-26
        相关资源
        最近更新 更多