Joe Scotto
Joe Scotto

Reputation: 10877

How to set max width of canvas to size of screen while keeping aspect ratio?

I'm using a canvas to load a base64 image. Currently I have it so it will just be the full size that the loaded image is. I'm wanting to have the canvas keep the aspect ratio of the image but only be a maximum width of the iphone screen I'm using it on. Right now it goes off the screen when loaded in.

The following is my canvas code:

// imageData is a base64 encoded string
this.base64Image = "data:image/jpeg;base64," + imageData;

// Load image on canvas
const nativeCanvas: HTMLCanvasElement = this.cameraCanvas
    .nativeElement;
const ctx = nativeCanvas.getContext("2d");

var image = new Image();
image.onload = function() {
    nativeCanvas.height = image.height;
    nativeCanvas.width = image.width;
    ctx.drawImage(image, 0, 0);
};
image.src = this.base64Image;
console.log("Image: ", image);

I am using this on a ionic-cordova app.

Upvotes: 1

Views: 1001

Answers (1)

enxaneta
enxaneta

Reputation: 33054

You will need to set the maxim width, for example: let maxW = 500. This may be your iPhone width. Then you can calculate the new new height of the image. I hope this is what you were asking.

image.onload = function() {
    nativeCanvas.width = maxW;
    nativeCanvas.height = (img.height * maxW)/img.width;
    ctx.drawImage(image, 0, 0, nativeCanvas.width, nativeCanvas.height);
};

Also you may use a conditional like if(img.width > maxW) recalculate the canvas height, else keep the canvas size = image size.

Upvotes: 3

Related Questions