【问题标题】:How to center a point of an image inside a canvas?如何在画布内居中图像的一个点?
【发布时间】: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 具有哪个高度或宽度,图像将始终完全保持其原始纵横比显示。我尚未能够实现的是将视图居中到图像的某个点。

在现实世界中,我有一个带有输入字段的表单。我也有表单的图像(扫描的),并且我知道原始图像上每个输入字段的坐标。因此,当我在文本字段中时,我想将该输入字段的坐标在图像上居中。当没有输入字段被聚焦时,我想用上面的代码显示现在显示的图像。

代码:

JS Bin

可视化

  1. 原图
  2. 我要居中的区域
  3. 居中区域的新图像

【问题讨论】:

  • 您可以添加一些所需行为的图像吗?
  • 我添加了一张图片。我希望这能说清楚。

标签: javascript canvas


【解决方案1】:

我解决了。这比我想象的要容易得多。假设我们有坐标:

leftUpper.x
leftUpper.y
rightLower.x
rightLower.y

那么我们可以做以下事情:

coordsCenterX = (coords.rightLower.x - coordsleftUpper.x) / 2;
coordsCenterY = (coords.rightLower.y - coordsLeftUpper.y) / 2;
coordsX = (coords.leftUpper.x + coordsCenterX) * ratio;
coordsY = (coords.leftUpper.y + coordsCenterY) * ratio;

centerShiftX += scaledImageWidth / 2 - coordsX;
centerShiftY += scaledImageHeight / 2 - coordsY;

所以基本上我们将图像的左上角设置为画布的中心,然后减去我们想要在画布中心看到的矩形的中心。

Updated JS Bin

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 2016-11-24
    • 2015-05-21
    • 2015-09-23
    • 1970-01-01
    • 2015-09-22
    • 2017-09-24
    • 2014-06-20
    相关资源
    最近更新 更多