首页 > 解决方案 > 如何在保持纵横比的同时将画布的最大宽度设置为屏幕大小?

问题描述

我正在使用画布加载 base64 图像。目前我有它,所以它只是加载图像的全尺寸。我想让画布保持图像的纵横比,但只是我正在使用它的 iphone 屏幕的最大宽度。现在它在加载时会消失在屏幕上。

以下是我的画布代码:

// 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);

我在 ionic-cordova 应用程序上使用它。

标签: htmlcordovacanvashtml5-canvasbase64

解决方案


您将需要设置最大宽度,例如:let maxW = 500. 这可能是您的 iPhone 宽度。然后您可以计算图像的新高度。我希望这是你问的。

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

您也可以使用条件,例如if(img.width > maxW)重新计算画布高度,否则保持画布大小 = 图像大小。


推荐阅读