首页 > 解决方案 > 如何在圆角容器中包含图像?

问题描述

我有这个图像,它位于一个 div 容器内。如您所见,图像本身并没有完全显示,因为图像的一部分由于边框半径使其成为圆形而保持隐藏。有没有办法显示这个隐藏的部分?我目前正在使用object-fit:cover,但这无济于事

这里

标签: htmlcssimage

解决方案


为了优化圆圈内使用的空间,我们需要查看图像的纵横比。例如,一个长但不是很高的图像应该尽可能多地占据圆圈的宽度。

此片段读取图像的自然宽度和高度,并计算 x 或 y 方向是否适合最大可能。它通过记住适合矩形的圆的直径与矩形的直径(和 vv)相同来做到这一点。

如果纵横比大于 1,我们会得到以下结果: 在此处输入图像描述

如果比率小于 1,我们会得到以下结果: 在此处输入图像描述

function scale() {
  const img = document.querySelector('.img');
  const w = img.naturalWidth;
  const h = img.naturalHeight;
  const circle = document.querySelector('.circle');
  let sizex = 'auto';
  let sizey = 'auto';

  let scale = circle.offsetWidth / Math.sqrt(w * w + h * h);
  if (w / h > 1) {
    sizex = w * scale + 'px';
  } else {
    sizey = h * scale + 'px';
  }
  circle.style.setProperty('--sizex', sizex);
  circle.style.setProperty('--sizey', sizey);
}
window.onload = scale;
window.onresize = scale;
.container {
  width: 100vw;
  height: 80vmin;
  background-color: red;
  position: relative;
}

.circle {
  position: absolute;
  top: 40vmin;
  left: 20vmin;
  width: 50vmin;
  height: 50vmin;
  background-color: transparent;
  border-radius: 50%;
  border-style: solid;
  background-image: url(https://picsum.photos/id/1015/300/400);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: var(--sizex) var(--sizey);
  background-color: white;
}

.img {
  opacity: 0;
  position: absolute;
}
<img class="img" src="https://picsum.photos/id/1015/300/400" />
<div class="container">
  <div class="circle">
  </div>
</div>

该片段有点基本,例如,如果您提前知道尺寸,您可以让 CSS 进行计算,而无需加载 img 来查找其自然宽度/高度。


推荐阅读