【问题标题】:How to set max width of canvas to size of screen while keeping aspect ratio?如何在保持纵横比的同时将画布的最大宽度设置为屏幕大小?
【发布时间】:2019-05-18 00:41:29
【问题描述】:

我正在使用画布加载 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 应用程序上使用它。

【问题讨论】:

    标签: html cordova canvas html5-canvas base64


    【解决方案1】:

    您需要设置最大宽度,例如: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) 等条件重新计算画布高度,否则保持画布大小 = 图像大小。

    【讨论】:

    • 成功了,但我遇到了一个问题,它实际上并没有缩放图像,它只是切断了它的一部分。
    • 您是否将drawImagectx.drawImage(image, 0, 0); 更改为ctx.drawImage(image, 0, 0, nativeCanvas.width, nativeCanvas.height);
    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多