This commit is contained in:
aihe 2024-05-12 12:04:11 +08:00
parent cacea1a704
commit 0865f1da12
2 changed files with 37 additions and 1 deletions

31
common/canvasUtil.js Normal file
View File

@ -0,0 +1,31 @@
/** 保持纵横比缩放图片,使图片的长边能完全显示出来。也就是说,可以完整地将图片显示出来。
* @param {Number} sx 固定盒子的x坐标,sy 固定盒子的y左标
* @param {Number} box_w 固定盒子的宽, box_h 固定盒子的高
* @param {Number} source_w 原图片的宽, source_h 原图片的高
* @return {Object} {drawImage的参数,缩放后图片的x坐标,y坐标,宽和高},对应drawImage(imageResource, dx, dy, dWidth, dHeight)
*/
const containImg = (sx, sy, box_w, box_h, source_w, source_h) => {
var dx = sx,
dy = sy,
dWidth = box_w,
dHeight = box_h;
if (source_w > source_h || (source_w == source_h && box_w < box_h)) {
dHeight = source_h * dWidth / source_w;
dy = sy + (box_h - dHeight) / 2;
} else if (source_w < source_h || (source_w == source_h && box_w > box_h)) {
dWidth = source_w * dHeight / source_h;
dx = sx + (box_w - dWidth) / 2;
}
return {
dx,
dy,
dWidth,
dHeight
}
}
export {
containImg
}

View File

@ -24,6 +24,7 @@
<script>
import { showLoading, showToast, hideLoading, canvasGetImageData, getImageInfo } from "@/common/untool"
import * as canvasUtil from "@/common/canvasUtil"
import * as printJob from './print/printJob'
@ -135,7 +136,11 @@ export default {
// ctx.fillStyle = 'rgba(255,255,255,1)';
ctx.clearRect(0, 0, w, h);
ctx.fillRect(0, 0, w, h);
ctx.drawImage(filePath, 0, 0, w, h);
let imgRect = canvasUtil.containImg(0, 0, w, h, res.width, res.height)
// 把原图缩放到 打印宽度的比例 绘制
ctx.drawImage(filePath, imgRect.dx, imgRect.dy, imgRect.dWidth, imgRect.dHeight);
ctx.draw(false, () => {
setTimeout( async ()=> {
let { data } = await canvasGetImageData({ canvasId: that.canvasId, width: w, height: h, })