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?