0

When reading documentation of Angular I found an information stating that DOM Elements should be altered by the Renderer2 class. I tried to update my project where I used ViewChild directive, but this way is not working with HTML Canvas Elements, normal HTML elements works like a charm. Is HTML Canvas Element modification not supported by Renderer2 ?

    @ViewChild('canvas_foreground', {static: true}) canvasForeground: ElementRef<HTMLCanvasElement>;
    @ViewChild('canvas_background', {static: true}) canvasBackground: ElementRef<HTMLCanvasElement>;
    wrapper: ElementRef<HTMLElement>;

    ngOnInit(): void {
        this.wrapper = this.el.nativeElement.querySelector('.canvases-wrapper');
        this.setWidthAndHeight();
        ...
    }

    setWidthAndHeight(): void {
        ...
        // working method
        this.renderer.setStyle(this.wrapper, 'width', this.screenWidth);
        this.renderer.setStyle(this.wrapper, 'height', this.screenHeight);

        // working method
        this.canvasBackground.nativeElement.width = this.screenWidth;
        this.canvasBackground.nativeElement.height = this.screenHeight;
        this.canvasForeground.nativeElement.width = this.screenWidth;
        this.canvasForeground.nativeElement.height = this.screenHeight;

        //not working method
        this.renderer.setStyle(this.canvasBackground.nativeElement, 'width', this.screenWidth);
        this.renderer.setStyle(this.canvasBackground.nativeElement, 'height', this.screenHeight);
        this.renderer.setStyle(this.canvasForeground.nativeElement , 'width', this.screenWidth);
        this.renderer.setStyle(this.canvasForeground.nativeElement, 'height', this.screenHeight);
     }
Kajetanoss
  • 159
  • 1
  • 2
  • 8
  • 1
    Not sure what's "not working". I've created a simple stackblitz repro and it all works as expected: https://stackblitz.com/edit/canvas-example-zibguh – TotallyNewb Jul 27 '21 at 17:03
  • In my case the size is not updated when using Renderer2, I'm using Angular 9. I found the problem. Instead of setStyle I should have used the setProperty method. Thanks for the example :) – Kajetanoss Jul 27 '21 at 17:23

0 Answers0