emis-sapp/common/canvasUtil.js
2024-05-31 18:42:15 +08:00

31 lines
999 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** 保持纵横比缩放图片,使图片的长边能完全显示出来。也就是说,可以完整地将图片显示出来。
* @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
}