简体   繁体   English

如何在画布内居中图像的一个点?

[英]How to center a point of an image inside a canvas?

Im having an image which im showing on a canvas.我有一个图像,显示在画布上。 The first challenge for me was to scale the image so that it always fits the parent div.我面临的第一个挑战是缩放图像,使其始终适合父 div。 I achieved that by doing this:我通过这样做实现了这一点:

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,
);

With that no matter which height or width my parent div has, the image will always show completely keeping its original aspect ratio.有了这个,无论我的父 div 有什么高度或宽度,图像将始终显示完全保持其原始纵横比。 What I yet havent been able to achieve is centering the view to a certain point of the image.我还没有能够实现的是将视图居中到图像的某个点。

In the real world im having a form with input fields.在现实世界中,我有一个带有输入字段的表单。 I also have an image of the form (its scanned) and I know the coordinates of each input field on the original image.我还有一张表单的图像(扫描的),我知道原始图像上每个输入字段的坐标。 So when Im in a textfield I want to center the coordinates of that input field on the image.因此,当我在文本字段中时,我想将该输入字段的坐标居中放置在图像上。 When no input field is focused I want to show the image as it is showing now with the above code.当没有输入字段被聚焦时,我想用上面的代码显示现在显示的图像。

Code:代码:

JS Bin JS斌

Visuatlization可视化

在此处输入图片说明

  1. Original Image原图
  2. The area I want to center我想居中的区域
  3. The new image with the centered area具有居中区域的新图像

I solved it.我解决了。 It was much easier than I thought.这比我想象的要容易得多。 Lets say we have coordinates:假设我们有坐标:

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

Then we can do the following:然后我们可以执行以下操作:

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;

So basically we set the left upper corner of the image to the center of the canvas and after that subtract the center of the rectangle we want to see on the center of the canvas.所以基本上我们将图像的左上角设置为画布的中心,然后减去我们想要在画布中心看到的矩形的中心。

Updated JS Bin更新了 JS Bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM