【问题标题】:How to cut a circular part from an image?如何从图像中剪切圆形部分?
【发布时间】:2018-12-24 20:19:12
【问题描述】:

我正在尝试使用 SVG 路径剪辑我的图像,但我的图像似乎不太适合。

这就是我想要实现的目标:

这就是我得到的:

这是我尝试过的代码:

.topbar-chat-img {
  width: 48px;
  height: 48px;
  object-fit: cover;
  clip-path: url(#topbar-img-svg);
}
<img src="https://picsum.photos/200/200?image=1069" class="topbar-chat-img" />

<svg>
                    <defs>
                        <clipPath id="topbar-img-svg">
                            <path class="svg-cls" d="M33,66A33.009,33.009,0,0,1,20.155,2.593,32.99,32.99,0,0,1,66,33a32.691,32.691,0,0,1-3.271,14.341,11.008,11.008,0,0,0-13.148,14.2A32.978,32.978,0,0,1,33,66Z"/>
                        </clipPath>
                    </defs>
                </svg>

我也试图改变 vievBox 和 svg 的大小,但我无法适应图像。

【问题讨论】:

  • 为什么是剪辑路径?而不仅仅是半径?
  • 再看看我要达到的效果,这不是一个简单的圆,是一个有切出路径的圆

标签: html css svg clip-path


【解决方案1】:

这是使用 SVG 的另一种更简单的方法:

body {
  background:pink;
}
<svg width="200" height="200">
  <defs>
    <mask id="hole">
      <circle r="100" cx="100" cy="100" fill="white"/>
      <circle r="50" cx="180" cy="180" fill="black"/>
    </mask>
  <pattern id="img" patternUnits="userSpaceOnUse" width="200" height="200">
    <image  xlink:href="https://picsum.photos/200/200?image=1069" x="0" y="0" width="200" height="200" />
  </pattern>
  </defs>
  <!-- create a rect, fill it with the image and apply the above mask -->
  <rect fill="url(#img)" width="100%" height="100%" mask="url(#hole)" />
</svg>

您也可以使用 CSS 和掩码来做到这一点:

body {
  background:pink;
}

img {
  border-radius:50%;
  -webkit-mask:radial-gradient(circle at calc(100% - 20px) calc(100% - 20px),transparent 50px,#fff 51px);
          mask:radial-gradient(circle at calc(100% - 20px) calc(100% - 20px),transparent 50px,#fff 51px);
  
}
&lt;img src="https://picsum.photos/200/200?image=1069" &gt;

另一种可以轻松调整圆位置的语法:

body {
  background:pink;
}

img {
  border-radius:50%;
  padding:1px;
  -webkit-mask:
    linear-gradient(#fff,#fff),
    radial-gradient(farthest-side,#fff 98%,transparent 100%) 
      bottom -30px right -30px/
      100px 100px no-repeat;
  -webkit-mask-composite:source-out;
  
  mask:
    linear-gradient(#fff,#fff),
    radial-gradient(farthest-side,#fff 98%,transparent 100%) 
      bottom -30px right -30px/
      100px 100px no-repeat;
  mask-composite:exclude;
  transition:1s;
}
img:hover {
  -webkit-mask-position:top -30px right -30px;
          mask-position:top -30px right -30px;
}
&lt;img src="https://picsum.photos/200/200?image=1069" &gt;

【讨论】:

  • 太棒了@temani,我有一个关于这个的问题,这可以跨浏览器工作吗?
  • @AtulRajput CSS 掩码版本适用于除 IE (caniuse.com/#feat=css-masks) 以外的任何地方,但 SVG 应该适用于 IE
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 2011-09-19
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多