找回密码
 立即注册
搜索
查看: 21|回复: 1

svg接力绘图演示

[复制链接]

1676

主题

3472

回帖

1万

积分

管理员

积分
14135
发表于 昨天 00:32 | 显示全部楼层 |阅读模式

1676

主题

3472

回帖

1万

积分

管理员

积分
14135
 楼主| 发表于 昨天 00:33 | 显示全部楼层
<style>
    #msvg {
        display: block;
        margin: auto;
        path {
            stroke-dasharray: var(--perimeter);
            stroke-dashoffset: var(--perimeter);
            fill: none;
            stroke: green;
            stroke-width: 2;
            animation: draw 4s var(--delay) linear forwards;
        }
        circle {
            stroke-dasharray: var(--perimeter);
            stroke-dashoffset: var(--perimeter);
            fill: none;
            stroke: green;
            stroke-width: 2;
            animation: draw 4s var(--delay) linear forwards, fill 2s calc(var(--delay) + 4s) forwards;
        }
    }
    .tMid { text-align: center; }
    @keyframes draw { to { stroke-dashoffset: 0; } }
    @keyframes fill { to { fill: lightgreen; } }
</style>

<svg id="msvg" width="400" height="400" viewBox="-200 -200 400 400" xmlns="http://www.w3.org/2000/svg">
    <path d="M-180 0 L0 -180 L180 0 L0 180Z"></path>
    <path d="M-88 -88 L88 -88 L88 88 L-88 88Z"></path>
    <circle x="0" y="0" r="86"></circle>
</svg>
<p class="tMid"><button type="button">再来一次</button></p>

<script>
    const paths = document.querySelectorAll('#msvg path');
    const circle = document.querySelector('#msvg circle');

    [...paths, circle].forEach((elm, key) => {
        elm.style.cssText += `
            --perimeter: ${Math.ceil(elm.getTotalLength())};
            --delay: ${key * 4}s;
        `;
    });

    function reStartAnimation() {
        [...paths, circle].forEach(elm => {
            elm.style.animation = 'none';
            setTimeout(() => {
                elm.style.animation = 'draw 4s var(--delay) linear forwards';
                if (elm.tagName === 'circle') {
                    elm.style.animation += ', fill 2s calc(var(--delay) + 4s) forwards';
                }
            });

        });
    }
</script>

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

协同嘉业科技有限公司 ( 京ICP备2024053108号-1 )

GMT+8, 2026-11-11 00:29 , Processed in 0.114557 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表