javascript - 在上传期间调整图像大小(Canvas 和 SimpleImage 库)
问题描述
我的目标是让用户上传本地图像。我在画布元素中绘制此图像。在此画布元素之上,我创建了另一个画布,用于在其上绘制框,以便框覆盖上传的图像。
我希望以特定尺寸上传图像,例如最大 100 宽度和最大 100 高度。仅以最大高度和最大宽度显示图像对我来说是不够的:100,它在上传过程中物理上需要调整大小。因为如果我把一张超大图片放在一个 100x100 的画布上,那么它上面的框就会变得非常小,我需要它们的大小相同,无论画布中的图像是什么大小。
以下是代码: HTML:
<div style="position: relative;">
<canvas id="can"
style="position: absolute; left: 0; top: 0; z-index: 0;max-width:80%;"></canvas>
<canvas id="box"
style="position: absolute; left: 0; top: 0; z-index: 1;max-width:80%;"></canvas>
</div>
<input type="file" multiple="false" accept="image/*" id="finput" onchange="upload()">
和 JS:
function upload() {
//Get input from file input
var fileinput = document.getElementById("finput");
//Make new SimpleImage from file input
image = new SimpleImage(fileinput);
//Get canvas
var canvas = document.getElementById("can");
//Draw image on canvas
image.drawTo(canvas);
}
我使用 simpleImage 库,因为它可以让我提取图像的 RGB 值。
解决方案
let originalWidth;
let originalHeight;
let imageWidth;
let imageHeight;
const load = result => {
return new Promise((fulfill, _reject) => {
let imageObj = new Image();
imageObj.onload = () => fulfill(imageObj);
imageObj.src = result;
});
}
const upload = () => {
const fileinput = document.getElementById("finput");
const canvas = document.getElementById("can");
let context = canvas.getContext("2d");
const reader = new FileReader();
reader.onload = event => {
Promise.all([
load(event.target.result)
])
.then(images => {
originalWidth = images[0].width;
originalHeight = images[0].height;
imageWidth = originalWidth;
imageHeight = originalHeight;
imageWidth = 200; // Fixed value
// Value proportional to width. Keeping to scale without distorting the image ( recommended )
imageHeight = originalHeight * (imageWidth / originalWidth);
context.drawImage(images[0], positionX, positionY, imageWidth, imageHeight);
})
}
reader.readAsDataURL(fileinput);
}
推荐阅读
- ios - 如何快速将参数传递给这种函数?
- html - 如何使用一个元素的孙子元素来切换前一个元素的孙子元素的类?
- python - 从 Excel 文件中绘制数据
- node.js - Mongoose 填充未提供连接结果
- c++ - g++:致命错误:无法执行'as':CreateProcess:没有这样的文件或目录编译终止
- android - Android Studio 无法在模拟器上安装应用
- django - Django-Form:在清理表单时向表单添加附加信息的问题
- javascript - 我试图在 $ 之后在屏幕上显示一个数字变量
- windows - 有什么方法可以从 MSBuild 中提取 compile_commands.json 吗?
- javascript - 如何通过 HTTP 请求在strapi中添加可重复组件