首页 > 解决方案 > 在VUE中渲染three.js画布而不使用外部变量或appendChild

问题描述

我尝试在 vue 设置中渲染三个 js 画布。但是由于 Vue 的状态管理模式,只有当我在 vue 状态管理之外设置画布相关变量时才能完成。

我看到了一个在 vue 状态环境中实现这一点的示例,但在这种情况下,必须在 vue 中而不是在 html/template 中创建 DOM 元素。

  1. 有没有一种方法可以在 vue 中创建三个画布而不使用 vue 之外的变量(这意味着使用 let scene,而不是 this.scene)?

或者

  1. 使用 vue 状态管理但不使用

    document.body.appendChild(this.renderer.domElement);
    

而是使用

this.renderer=new THREE.WebGLRenderer({canvas:this.canvas})

谢谢

我的Vue代码如下。

<template>
    <div>
        <canvas id="myCanvas"></canvas>
    </div>
</template>

<script>
import * as THREE from 'three'



export default {
data(){
    return{
        canvas:null,
        pointArr:[],
        scene:null,
        camera:null,
        renderer:null,
        cube:null

    }
},
computed:{

},
methods:{

init(){
this.scene =new THREE.Scene();
this.canvas=document.querySelector('#myCanvas');
this.canvas.width=innerWidth;
this.canvas.height=innerHeight;

this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
this.renderer=new THREE.WebGLRenderer({canvas:this.canvas})
this.renderer.setSize( window.innerWidth, window.innerHeight );

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

this.cube= new THREE.Mesh( geometry, material );
this.camera.position.z = 5
this.scene.add(this.cube);


},

animate(){
    requestAnimationFrame( this.animate );
    this.cube.rotation.x += 0.1;
    this.cube.rotation.y += 0.1;
    this.renderer.render(this.scene, this.camera);
}

},

mounted(){


this.init()
this.animate();
// window.addEventListener()
},
created(){



},

unmounted(){
//window.removeEvenetListener()
}




}
</script>

这部分一直抛出错误

this.renderer.render(this.scene, this.camera);

在此处输入图像描述

标签: vue.jsthree.js

解决方案


感谢您提供错误屏幕截图。似乎您将无法使用状态变量来存储您的值。

这是因为 Vue 实际上将您的状态变量转换为可观察的,以使反应性起作用。Three.js 抱怨您分配的变量已将其值从 # 更改为 [object Object],这表明一旦将其分配给类变量,Vue 更改了它的值,现在 Three.js 不再可以使用它。

这就是为什么您看到的所有其他示例都是在 Vue 组件之外定义它的原因。


推荐阅读