我正在使用画布加载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);
我正在离子cordova应用程序上使用它。
答案 0 :(得分:2)
您将需要设置最大宽度,例如: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)
重新计算画布高度,否则保持画布大小=图片大小。