2D
2025年02月08日
一、认识
二、思路
三、实现
function calculateNewDimensions(imageWidth, imageHeight, targetSize) {
const aspectRatio = imageWidth / imageHeight;
let newWidth, newHeight;
if (aspectRatio > 1) {
newWidth = targetSize;
newHeight = targetSize / aspectRatio;
} else {
newHeight = targetSize;
newWidth = targetSize * aspectRatio;
}
return { newWidth, newHeight };
}
function scaleImageTo(
ctx,
imageEl,
imageWidth,
imageHeight,
targetSize,
) {
const { newWidth, newHeight } = calculateNewDimensions(
imageWidth,
imageHeight,
targetSize
);
ctx.clearRect(0, 0, newWidth, newHeight);
ctx.drawImage(
imageEl,
0,
0,
imageWidth,
imageHeight,
0,
0,
newWidth,
newHeight
);
}