在CSS circle()半径中似乎无法正确计算

问题描述 投票:1回答:1

每当我尝试使用CSS circle()函数进行一些剪辑时,就已经困扰了我一段时间:

.red {
  	width: 200px;
        height: 300px;
        background: red;
        clip-path: circle(69%);  /*barely cuts off the corners of the .red div */
}

/*  the full circle will enclose the entire box at around 71% or (sqrt(2)/2 * 100%)
 per Mozilla documentation and not at 100% as one might expect */
<div class='red'></div>

半径似乎从未像我期望的那样计算过。在查看Mozilla MDN参考(https://developer.mozilla.org/en-US/docs/Web/CSS/basic-shape)时,似乎他们的计算如下:

enter image description here

对我来说似乎不正确。我想他们会计算如下包围元素矩形(div,img等)的圆周半径:

enter image description here

但是似乎并非如此。任何人都可以阐明这一点。这是某种错误,还是我在这里不理解?

css geometry clip clip-path radius
1个回答
0
投票

它的定义就是这样,它们从来都不意味着要计算您显示的半径。也是in the specification

为了更好地理解,我们考虑一个正方形。如果您将50%作为值,则可以得到一个完美的圆

.red {
  width: 200px;
  height: 200px;
  background: red;
  clip-path: circle(50%);
  border:2px solid;
  box-sizing:border-box;
}
<div class='red'></div>

背后的想法是考虑下图:

enter image description here

R是您正在计算的'c'(绿线),r是所使用的参考(紫色线)。您可以轻松地看到r = R/sqrt(2)R = sqrt(w² + h²)。结合两者将给我们:

r = sqrt(w² + h²)/sqrt(2)

您在MDN页面中看到的是哪个公式。为了覆盖整个正方形,我们使用r*sqrt(2) = r*1.41

.red {
  width: 200px;
  height: 200px;
  background: red;
  clip-path: circle(calc(50% * 1.38)); /* a little smaller thab 1.4 to better see*/
  border:2px solid;
  box-sizing:border-box;
}
<div class='red'></div>

相同的逻辑适用于宽度和高度不同但参考保持不变的非正方形形状:

r = sqrt(w² + h²)/sqrt(2)
© www.soinside.com 2019 - 2024. All rights reserved.