繁体   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