html - 如何在保持纵横比的同时将画布的最大宽度设置为屏幕大小?
问题描述
我正在使用画布加载 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 应用程序上使用它。
解决方案
您将需要设置最大宽度,例如: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)
重新计算画布高度,否则保持画布大小 = 图像大小。
推荐阅读
- wordpress - 使用 wordpress 为自由职业者网站创建后期项目功能
- python - CSV 文件的文件名不能使用 Python 变量
- python - 将嵌套的 JSON streamind 数据转换为 ndjson
- python - 需要去掉单引号
- python - 绘制半径为 R 的球体
- javascript - 如何使用函数 true 在 jquery 步骤中验证隐藏的空字段
- android - SHA-1 问题的 Android Studio v4.1 签名报告
- node.js - 在 Selenium Grid 4 alpha 6 中访问 chrome 驱动程序开发工具,
- html - 我如何将图像作为背景放在 reatcjs 上的多个组件下
- javascript - 函数没有改变外部变量