核心步骤
- 获取原始图片尺寸
- 计算缩放比例
- 计算新尺寸
新宽度 = 原始宽度 × 缩放比例
新高度 = 原始高度 × 缩放比例
- 绘制图片
使用 drawImage()
方法绘制缩放后的图片
代码实现
// 获取Canvas上下文
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");// 创建图片对象
const img = new Image();
img.src = "your-image.jpg";img.onload = function () {// 1. 获取原始尺寸const originalWidth = img.width;const originalHeight = img.height;// 2. 设置目标区域尺寸(示例:Canvas尺寸)const targetWidth = canvas.width;const targetHeight = canvas.height;// 3. 计算缩放比例(保持比例)const scale = Math.min(targetWidth / originalWidth, targetHeight / originalHeight);// 4. 计算新尺寸const newWidth = originalWidth * scale;const newHeight = originalHeight * scale;// 5. 居中绘制const x = (targetWidth - newWidth) / 2;const y = (targetHeight - newHeight) / 2;// 绘制缩放后的图片ctx.drawImage(img, x, y, newWidth, newHeight);
};
关键参数说明
参数 | 说明 |
---|
scale | 取宽度比和高宽比的最小值,确保图片完整显示 |
newWidth/Height | 按比例计算后的新尺寸 |
x, y | 居中定位坐标(可选) |