簡體   English   中英

如何在畫布內居中圖像的一個點?

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

我有一個圖像,顯示在畫布上。 我面臨的第一個挑戰是縮放圖像,使其始終適合父 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斌

可視化

在此處輸入圖片說明

  1. 原圖
  2. 我想居中的區域
  3. 具有居中區域的新圖像

我解決了。 這比我想象的要容易得多。 假設我們有坐標:

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;

所以基本上我們將圖像的左上角設置為畫布的中心,然后減去我們想要在畫布中心看到的矩形的中心。

更新了 JS Bin

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM