簡體   English   中英

如何在 HTML Canvas 圓中居中圖像?

[英]How to center an image in a HTML Canvas Circle?

我對 canvas 非常陌生,所以我對它的工作原理知之甚少。 這是我在屏幕中間繪制的圓圈的代碼。

      ctx.save();
      ctx.beginPath();
      ctx.arc(canvas.width / 2, canvas.height / 2, radius, 0, 2 * Math.PI);

      ctx.strokeStyle = "#2465D3";
      ctx.stroke();
      ctx.clip();

      ctx.drawImage(imageFile, 200, 200, 500, 500);
      ctx.restore();
      ctx.stroke();

我想在圓圈內顯示一張圖片。 圖片顯示在帶有此代碼的錯誤 position 的圓圈中。 我希望圖片位於圓圈的中心,例如:

在此處輸入圖像描述

根據drawImage()的語法,我需要ctx.drawImage(image, dx, dy, dWidth, dHeight)中的dxdy到 position 正確地在 canvas 上的圖像(在圓的中心)。

我有什么辦法可以在不進行各種畢達哥拉斯計算的情況下將圖片放在圓的中心?

為什么我要這樣做?

我找不到合適的圖片坐標並繼續前進,因為圓的半徑不是恆定的,因此無法正常工作。 每次圓的半徑發生變化時,我都需要為圖片找到合適的坐標,以使圖片保持在圓的中間。

我的思考過程是找到圓在這張圖片中所形成的正方形的角坐標

圖表

然后測量該點與 canvas 寬度之間的距離。

我認為必須有更好的方法來做到這一點。 有一個更好的方法嗎? 我在 React 應用程序中使用它。

您的圖像必須具有 x 和 y position 等於圓形。 imagem 的高度和寬度必須為 2r。

x = canvas.width / 2;
y = canvas.height / 2
ctx.save();
ctx.beginPath();
ctx.arc(x,y, radius, 0, 2 * Math.PI);

ctx.strokeStyle = "#2465D3";
ctx.stroke();
ctx.clip();

ctx.drawImage(imageFile, x, y, 2 * radius, 2 * radius);
ctx.restore();
ctx.stroke();

在此處輸入圖像描述

這里canvas.width / 2canvas.height/ 2是圓心的坐標。

      ctx.drawImage(
        oneMoreRound,
        canvas.width / 2,
        canvas.height / 2,
        radius * 2,
        radius * 2
      );

只有通過上面的代碼才能將圖像的左上角放置到圓的中心,如下所示:

在此處輸入圖像描述

xy坐標中減去半徑,將圖像的左上角放在圓將創建的正方形的左上角。 如果圖像是正方形,這會將圖像放在右側 position 中。

在此處輸入圖像描述

這是解決方案

      ctx.drawImage(
        oneMoreRound,
        canvas.width / 2 - radius,
        canvas.height / 2 - radius,
        radius * 2,
        radius * 2
      );

暫無
暫無

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

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