vue中调用设备底层功能(照相机)并展示
首先在src根目录下创建utils文件夹,复制以下代码,文件名Tools.js
class Tools {
static reduceImgSize = (file, maxWidth = 800, maxHeight = 800) => {
return new Promise((reslove, rej) => {
let img = new Image();
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
img.onload = function() {
const originWidth = this.width;
const originHeight = this.height;
let targetWidth = originWidth,
targetHeight = originHeight;
// 图片尺寸超过maxWidth x maxHeight的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// 清除画布
// 图片压缩
//判断宽高大小来旋转画布
if (targetHeight > targetWidth) {
canvas.width = targetHeight;
canvas.height = targetWidth;
context.translate(0, targetWidth);
context.rotate((-90 * Math.PI) / 180);
context.clearRect(0, 0, targetWidth, targetHeight);
} else {
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
}
context