马黑PHP整站系统

css+svg动态绘制四叶草

位置: 首页 > 代码集锦[ 发布时间: 2024.10.4  作者: 马黑  阅读: 35 ]

下面的代码使用svg的path路径绘制四叶草,路径由四个三次贝塞尔曲线拼凑而成,简洁而高效。路径动画通过两个CSS动画驱动,一个绘制、另一个擦除,动画的衔接由JS控制,两个动画间的时间间隔为两秒。CSS @keyframes动画设计的关键点在于 stroke-dashoffset 的准确取值,最大偏移量数值的确定可以在绘制好路径后使用 path.getTotalLength() 语句计算。

<style>
#clover {
	fill: none;
	stroke: green;
	stroke-width: 2;
	stroke-dasharray: 1478;
	animation: draw 10s linear forwards;
}
@keyframes draw {
	from { stroke-dashoffset: 1478; }
	to { stroke-dashoffset: 0; }
}
@keyframes erase {
	from { stroke-dashoffset: 0; }
	to { stroke-dashoffset: 1478; }
}
</style>

<svg width="400" height="400" fill="none">
	<line x1="0" y1="50%" x2="100%" y2="50%" stroke="silver" />
	<line x1="50%" y1="0" x2="50%" y2="100%" stroke="silver" />
	<path id="clover" d="M200 200 C50 0,350 0,200 200 C50 400,350 400,200 200 C0 50,0 350,200 200 C400 50,400 350,200 200" />
</svg>

<script>
var drawing = true;
clover.onanimationend = () => {
	setTimeout (() => {
		clover.style.animationName = ['draw','erase'][+drawing];
		drawing = !drawing;
	}, 2000);
};
</script>

效果:

前一篇: svg创意图案:来自火星的礼物
下一篇: 没有了

发表评论:

       

评论列表 [1条]

#1 | 悄然 于 2024-10-4 20:40 发布: 这个想法是太神奇了。。真像看动画片似的,绘制过程相当流畅,还会擦除重绘,智能又灵动

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com