I tried to render three js canvas within vue set up. But due to Vue's statemanagement pattern, it could be done only when I set the canvas related variables outside of vue state management.
I saw an example which achieved this within vue state environment but in this case, DOM element had to be created within vue not in html/template.
- Is there a way that I could create three canvas in vue not using variables outside of vue (it means use let scene, not this.scene)?
or
using vue state management but not using
document.body.appendChild(this.renderer.domElement);
rather using
this.renderer=new THREE.WebGLRenderer({canvas:this.canvas})
Thank you
My Vue code is as below.
<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 part keeps throwing an error
this.renderer.render(this.scene, this.camera);
