Angular | Setting up a custom canvas

Hello,

First thing first, I’m very new to ThreeJS.

I’m following the tutorial of this guy to understand the basics.

The problem is that he uses “document.body.appendChild(this.renderer.domElement)” and that creates a canvas I can’t modify with the CSS of my component.
So what I’m trying to do is to create my own canvas in the HTML of my component and then use this canvas as the main canvas.

But I’m struggling to do it, so any help would be very nice :blush:

Component.html :

<canvas #myCanvas id="myCanvas"></canvas>

Component.css :

#myCanvas { 
  width: 100vw; 
  height: 100vh; 
  display: block; 
}

Component.ts :

 export class Scene3dComponent implements OnInit {

   scene = new THREE.Scene()

   camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)

   @ViewChild('myCanvas', { static: true })
   public myCanvas: ElementRef<HTMLCanvasElement>;
   canvas = this.myCanvas.nativeElement

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

   constructor() { }

   ngAfterViewInit(){
     this.startScene();
   }

   startScene() {
     this.renderer.setClearColor('#E5E5E5')
     this.renderer.setSize(window.innerWidth, window.innerHeight)
     this.renderer.render(this.scene, this.camera)

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

     window.addEventListener('resize', () => {
       this.renderer.setSize(window.innerWidth, window.innerHeight)
       this.camera.aspect = window.innerWidth / innerHeight
       this.camera.updateProjectionMatrix();
     })
   }
}

The error I’m getting is “TypeError: Cannot read property ‘nativeElement’ of undefined”

for all people with this issue, I solved it by setting appendChild on the afterViewInit hook of angular and using the Renderer2 angular service on the constructor.

constructor(private ngRenderer:Renderer2){ }
ngAfterViewInit(){ this.ngRenderer.appendChild(this.myRenderer.nativeElement,this.renderer.domElement) }