从两个重叠的 HTML 元素逆向工程 CSS `background-position`

Reverse-engineer CSS `background-position` from two overlapping HTML elements

我有一个项目,用户可以在其中指定任意图像,稍后用作元素的背景图像。用户必须能够将图像定位在要应用图像的宿主元素中,以确保图像中需要显示的部分实际上是可见部分。

SitePoint notes the following 关于 CSS background-position 属性 的行为:

Note that when the background-position is defined with a percentage value, that position refers to both the element itself and the corresponding point on the background-image. For example, a background-image with background-position values of 50% 50% will place the point of the image that’s located at 50% of the image’s width and 50% of the image’s height at a corresponding position within the element that contains the image. In the above case, this causes the image to be perfectly centered. This is an important point to grasp—using background-position isn’t the same as placing an element with absolute position using percentages where the top-left corner of the element is placed at the position specified.

假设您有两个 HTML 元素。第一个是一个大元素,表示稍后用作背景位置的图像。第二个是位于第一个元素之上的较小元素,代表将来要应用背景图像的元素。

+-----------------------+ <-- Y1
| Image Placeholder     |
|                       |
| +-----------------------+ <-- y1
| | Container Placeholder |
| +-----------------------+ <-- y2
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
+-----------------------+ <-- Y2

给定每个元素的顶部和底部的 y 坐标,如何计算正确的百分比以保持图像的正确部分在应用了背景图像的最终元素中可见?

让我们采用原始可视化,为我们正在寻找的百分比位置的两个点添加变量:

      +-----------------------+ <-- Y1
      | Image                 |
      |                       |
      |         +-----------------------+ <-- y1
Y3 -->|   y3 -->| Container             |
      |         +-----------------------+ <-- y2
      |                       |
      |                       |
      |                       |
      |                       |
      |                       |
      |                       |
      +-----------------------+ <-- Y2

根据定义,这两点(图像上的一个点和容器上的一个点)必须位于同一位置。这两个百分比必须相等。因此:

Y_3 = y_3

下一步似乎是定义这两个目标点。假设其 top-left 角位于坐标 [0,0]:

处,这证明对于两个元素中较大的一个更容易

Y_3=pY_2

其中 p 表示我们正在寻找的百分比。

这个等式看起来几乎适用于较小的元素,除了这个元素不是从点 [0,0] 开始。相反,它从 [x1,y1] 点开始。 (我们可以安全地忽略它的 x 原点,因为我们只关心 y 百分比。)

校正此偏移量可得出此等式:

y_3=p(y_2-y_{1}) + y_{1}

代入我们原来的等式,我们得到:

pY_2=p(y_2-y_1) + y_1

现在剩下的就是求解p;完成后,我们得到这个最终等式:

p=\frac{y_1}{Y_2 - (y_2-y_1)}

Here is a jsfiddle example 这个等式的作用。上下拖动黄色元素可以看到动态计算的百分比(输出在图像下方)。红色刻度线是相同百分比的视觉指示器。