SVG 动画 - 来自中心的 SVG 的 CSS 悬停动画
Posted
技术标签:
【中文标题】SVG 动画 - 来自中心的 SVG 的 CSS 悬停动画【英文标题】:SVG Animation - CSS Hover Animation For SVG From The Center 【发布时间】:2021-02-02 02:50:03 【问题描述】:我在GSAP中做过这个效果这里是Codepen作为参考:
https://codepen.io/whitelionx/full/vYGQqBZ
const svgs = document.querySelectorAll("svg");
svgs.forEach((svg) =>
const tl = gsap
.timeline(
defaults: ease: "power1.in" ,
paused: true
)
.to(svg.children[0], drawSVG: "50% 50%" )
.from(svg.children[1], drawSVG: "0% 0%" , 0);
svg.addEventListener("mouseenter", () => tl.play());
svg.addEventListener("mouseleave", () => tl.reverse());
);
现在我想只用 CSS 来做,这样当我悬停我的 svg 时,我会得到相同的效果,这是我的代码沙箱:
https://codesandbox.io/s/xenodochial-benz-17lss?file=/src/styles.css
【问题讨论】:
【参考方案1】:我已经修改了一些东西来为 stroke-dasharray 设置动画。
body
background: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
svg
width: 50px;
height: 50px;
margin: 25px;
.circle
stroke-dasharray: 28.3,0,28.3;
transform-origin: 50% 50%;
transform: rotate(180deg);
transition: stroke-dasharray 0.5s linear;
.line
stroke-dasharray: 20;
stroke-dashoffset: 20;
transition: stroke-dashoffset 0.5s linear;
svg:hover .circle
stroke-dasharray: 0,56.0;
svg:hover .line
stroke-dashoffset: 0;
<svg
version="1.1"
shape-rendering="auto"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 20 20"
xml:space="preserve">
<path class="circle" fill="none" stroke="#FFFFFF" stroke-miterlimit="10" d="M10,1c5,0,9,4,9,9s-4,9-9,9s-9-4-9-9S5,1,10,1z"/>
<path class="line" fill="none" stroke="#FFFFFF" stroke-miterlimit="10" d="M10,0v20"/>
</svg>
【讨论】:
【参考方案2】:与此同时,我也这样做了,现在由于您的回答,我对 css 动画有了更好的理解:D 开箱即用
body
background: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
svg
width: 50px;
height: 50px;
margin: 25px;
cursor: pointer;
.circle
stroke-dasharray: 56.6;
stroke-dashoffset: 0;
transform-origin: 50% 50%;
transition: stroke-dashoffset 0.3s linear, transform 0.3s linear;
.line
stroke-dasharray: 20;
stroke-dashoffset: 20;
transition: stroke-dashoffset 0.3s linear;
svg:hover .circle
stroke-dashoffset: 56.6;
transform: rotate(180deg);
svg:hover .line
stroke-dashoffset: 0;
<svg
version="1.1"
shape-rendering="auto"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 20 20"
enable-background="new 0 0 20 20"
xml:space="preserve"
>
<path
class="circle"
fill="none"
stroke="#FFFFFF"
stroke-miterlimit="10"
d="M10,1c5,0,9,4,9,9s-4,9-9,9s-9-4-9-9S5,1,10,1z"
></path>
<path
class="line"
fill="none"
stroke="#FFFFFF"
stroke-miterlimit="10"
d="M10,0v20"
></path>
</svg>
【讨论】:
以上是关于SVG 动画 - 来自中心的 SVG 的 CSS 悬停动画的主要内容,如果未能解决你的问题,请参考以下文章