【发布时间】:2019-12-24 04:10:45
【问题描述】:
我有一张我在画布上显示的图像。对我来说,第一个挑战是缩放图像以使其始终适合父 div。我通过这样做实现了这一点:
const horizontalRatio = ctx.canvas.width / image.width;
const verticalRatio = ctx.canvas.height / image.height;
const ratio = Math.min(horizontalRatio, verticalRatio);
const centerShiftX = (ctx.canvas.width - image.width * ratio) / 2;
const centerShiftY = (ctx.canvas.height - image.height * ratio) / 2;
const scaledImageWidth = image.width * ratio;
const scaledImageHeight = image.height * ratio;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(
image,
0,
0,
image.width,
image.height,
centerShiftX,
centerShiftY,
scaledImageWidth,
scaledImageHeight,
);
这样,无论我的父 div 具有哪个高度或宽度,图像将始终完全保持其原始纵横比显示。我尚未能够实现的是将视图居中到图像的某个点。
在现实世界中,我有一个带有输入字段的表单。我也有表单的图像(扫描的),并且我知道原始图像上每个输入字段的坐标。因此,当我在文本字段中时,我想将该输入字段的坐标在图像上居中。当没有输入字段被聚焦时,我想用上面的代码显示现在显示的图像。
代码:
可视化
- 原图
- 我要居中的区域
- 居中区域的新图像
【问题讨论】:
-
您可以添加一些所需行为的图像吗?
-
我添加了一张图片。我希望这能说清楚。
标签: javascript canvas