如何为头像图像创建星形?

How do I create star shape for avatar image?

我想为用户头像创建星形。 我不知道如何填充这种形状的图像。

我的代码:

#star {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid #05ed08;
  position: relative;
}
#star:after {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-top: 100px solid #05ed08;
  position: absolute;
  content: "";
  top: 30px;
  left: -50px;
}
<
<div id="star"></div>

我想要一张介于 div 之间的图像。

I want an image here between div.

有几种方法可以解释上述陈述 - (1) 你想用图像填充形状,将图像限制在形状的边界内并剪掉任何额外的部分,或者 (2) 你只想在星星上放一张图片。


对于案例 1: 如果您需要创建如此复杂的形状并且还需要填充图像,那么最好的选择是 使用 SVG 而不是 CSS.

SVG 允许更好地控制形状,将图像保持在形状的边界内,并将悬停(点击区域)限制在形状的边界内。

svg {
  width: 200px;
  height: 200px;
}
path {
  fill: url(#g-image);
}
<svg viewBox='0 0 100 100'>
  <defs>
    <pattern id='g-image' width='100' height='100' patternUnits='userSpaceOnUse'>
      <image xlink:href='https://placeimg.com/100/100/animals' width='100' height='100' />
    </pattern>
  </defs>
  <path d='M0,25 L33,25 50,0 66,25 99,25 75,50 99,75 66,75 50,100 33,75  0,75 25,50z' />
</svg>


对于案例 2: 或者如果您只是想 放置图像形状的顶部然后你可以使用问题本身给出的 CSS 并将图像绝对放在它的顶部。几件值得注意的事情是(1)很难使使用边框创建的形状(例如这些方法)具有响应性(2)图像应该具有固定的高度和宽度,否则很有可能会溢出并且在星形之外也可见。

.wrapper{
  position: relative;
  width: 200px;
  height: 260px;
  border: 1px solid;
}
#star {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  border-left: 100px solid transparent;
  border-right: 100px solid transparent;
  border-bottom: 200px solid #05ed08;
  position: relative;
}
#star:after {
  width: 0;
  height: 0;
  border-left: 100px solid transparent;
  border-right: 100px solid transparent;
  border-top: 200px solid #05ed08;
  position: absolute;
  content: "";
  top: 60px;
  left: -100px;
}
img{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}
<div class='wrapper'>
  <div id='star'></div>
  <img src='http://placeimg.com/100/100/animals' />
</div>