如何在 VueJS 中使用 ThreeJS

WMo*_*iro 0 three.js vue.js

我想使用threeJS,所以我用npm i Three --save 安装它。我遵循了 ThreeJS 文档中的基本教程,但出现错误。

  mounted () {
    this.initThree();
  },
  methods: {
    initThree() {
      this.scene = new THREE.Scene();
      this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

      this.renderer = new THREE.WebGLRenderer( { canvas: document.getElementById( "background" ), alpha: true, antialias: true } );
      this.renderer.setSize( window.innerWidth, window.innerHeight );

      let geometry = new THREE.BoxGeometry( 1, 1, 1 );
      let material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
      this.cube = new THREE.Mesh( geometry, material );
      this.scene.add( this.cube );

      this.camera.position.z = 5;
      this.animate()

    },

    animate() {

      this.cube.rotation.x += 0.01;
      this.renderer.render( this.scene, this.camera );
      requestAnimationFrame( this.animate() );

    }
  }
}
Run Code Online (Sandbox Code Playgroud)

错误

soj*_*oju 5

您的问题与 VueJS /ThreeJs 无关,您应该简单地修复这一行:

requestAnimationFrame( this.animate() );
Run Code Online (Sandbox Code Playgroud)

它应该是 :

requestAnimationFrame(this.animate)
Run Code Online (Sandbox Code Playgroud)

请阅读有关回调的更多信息:https : //developer.mozilla.org/en-US/docs/Glossary/Callback_function

编辑:您可以尝试 TroisJS,轻松将 ThreeJS 与 VueJS 集成:https : //github.com/troisjs/trois

  • 因为有括号,animate() 会被立即调用,没有括号它会被 requestAnimationFrame 调用。https://developer.mozilla.org/en-US/docs/Glossary/Callback_function (5认同)