1

I would like to load the image and adjust the canvas size according to image dimensions.

Currently, the code is the following:

canvas = null;
  maxWidth = 800;
  canvasWidth = 200;
  canvasHeight = 200;

  constructor() { }

  loadImage(src) {
    return new Promise((resolve, reject)=> {
      console.log(src);

      var img = new Image();
      img.onload = () => resolve(img);
      img.src = src;
    });
  }


  ngOnInit() {
    var src = "example_image_url";
    this.canvas = document.getElementById('stage');
    let ctx = this.canvas.getContext("2d");
    this.loadImage(src).then(img => {
      let width = img.width;
      let height = img.height;
      if (width > this.maxWidth) {
        const scalingFactor = width / this.maxWidth;
        width = this.maxWidth;
        height /= scalingFactor;
        this.canvasWidth = width;
        this.canvasHeight = height;
      }
      ctx.drawImage(img,0,0, this.canvasWidth, this.canvasHeight);
    });
}

The canvas is defined as follows:

<canvas id="stage" [width]="canvasWidth" [height]="canvasHeight"></canvas>

When the image is loaded, it is not visible. If canvasWidth and canvasHeight doesn't change, the image is displayed. Does anyone know how to correctly load the image and readjust the canvas size?

Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286
  • Possible duplicate of [How to resize html canvas element?](https://stackoverflow.com/questions/331052/how-to-resize-html-canvas-element) – TheUnreal Oct 23 '19 at 06:49
  • I wouldn't say it is the duplicate as the suggested answer is related to javascript. I am not sure if this is angular-specific problem or it is caused by something else. – Niko Gamulin Oct 23 '19 at 07:05

1 Answers1

0

Unfortunately you can't bind Width and Height to a canvas because after your canvas gets rendered even changing the this.canvasWidth or this.canvasHeight it wont have an effect on the canvas , since you have the ctx element on your angular scope you can access the canvas and change it's value and it will render your image

if (width > this.maxWidth) {
    const scalingFactor = width / this.maxWidth;
    width = this.maxWidth;
    height /= scalingFactor;
    ctx.canvas.width = width;
    ctx.canvas.height = height;
}
ctx.drawImage(img,0,0, ctx.canvas.width, ctx.canvas.height);
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Tiago Silva
  • 2,299
  • 14
  • 18