使用自定义 svg 更改按钮的形状

Change shape of a button with custom svg

我有一个带有轮播滑块库的网站。问题是,每个滑块都有一个带有边框半径的圆形按钮,当我单击一个按钮时,我将其分配为 'active' class,因此当处于活动状态时,我将按钮变大。但我也想改变它的形状,让它看起来像一颗星星。我认为将 svg 与 clipPath 放在一起可以解决问题,但我没有工作。如果有人能告诉我如何让它改变它的形状,如果它是任何图书馆之类的,它会对我有很大帮助。

这是我尝试过的:

<button>
    <svg class="star2svg">
        <defs>
            <clipPath id="clipStar">
                <path class="star2" id="star2" d="M325.07,30.69l80.91,163.95l180.93,26.29c18.09,2.63,25.31,24.86,12.22,37.62L468.22,386.16l30.91,180.2
                c3.09,18.02-15.82,31.76-32,23.25l-161.83-85.08l-161.83,85.08c-16.18,8.51-35.09-5.23-32-23.25l30.91-180.2L11.45,258.55
                c-13.09-12.76-5.87-34.99,12.22-37.62l180.93-26.29l80.91-163.95C293.61,14.3,316.98,14.3,325.07,30.69z"/>
            </clipPath>
        </defs>
    </svg>
</button>

想这样设计:

button {
    width: 0.8em;
    height: 0.8em;
    border: none;
    border-radius: 50%;
    transition: 0.2s ease-out;
    position: relative;
    clip-path: url('#clipStar');

    .star2svg {
        position: absolute;
        left: 0;
        right: 0;
        display: block;
        width: 100%;
        height: 100%;
    }
}

svg 元素需要一个 viewBox 来知道从哪里开始显示内容以及从哪里剪裁内容。

在这种情况下,您的 viewBox 大约是 650x650:

.star2svg {
  width: 25px;
}
<button>
    <svg class="star2svg" viewBox="0 0 650 650">
        <path d="M325.07,30.69l80.91,163.95l180.93,26.29c18.09,2.63,25.31,24.86,12.22,37.62L468.22,386.16l30.91,180.2 c3.09,18.02-15.82,31.76-32,23.25l-161.83-85.08l-161.83,85.08c-16.18,8.51-35.09-5.23-32-23.25l30.91-180.2L11.45,258.55
                c-13.09-12.76-5.87-34.99,12.22-37.62l180.93-26.29l80.91-163.95C293.61,14.3,316.98,14.3,325.07,30.69z"></path>
    </svg>
</button>

您可以通过 css path() 函数 swap/transition svg 路径形状。

对于 transitions/morphing,您需要两种形状具有完全相同数量的命令。 Css 技巧:CSS 中的动画 SVG 路径变化

圆圈和星形之间的过渡可以通过以下方式完成:

  • 将星形路径减少为具有 10 个点的多边形
  • 圆角由stroke-linecaps/stroke-linejoin属性实现
  • 初始圆形是通过将所有 10 个点对齐并应用更大的 stroke-width 创建的:M50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1z

例子

.btn {
  appearance: none;
  -webkit-appearance: none;
  font-size: 10vw;
  background: none;
  padding: 0;
  border: none;
  color: #000;
  cursor: pointer;
}

.btnSvg {
  display: inline-block;
  height: 1em;
}

.btn .btnSvgPath {
  transition: 0.3s;
  border: none;
  stroke-width: 75;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.btn:hover .btnSvgPath {
  d: path('M50,77L23.3,91l5.1-29.7l-21.6-21L36.7,36L50,9l13.3,27l29.8,4.3l-21.6,21L76.7,91L50,77z');
  stroke-width: 5;
  color: gold;
}
<button class="btn">
    <svg class="btnSvg" viewBox="0 0 100 100" >
        <path class="btnSvgPath" d="M50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1L50,53.1z" fill="currentColor" stroke="currentColor" />
    </svg>
</button>