简体   繁体   中英

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. 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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