css新学的实现蚂蚁转圈

36 阅读1分钟
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>蚂蚁绕圈动画</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        .shape {
            width: 150px;
            height: 150px;
            border: 2px dashed darkgray;
            border-radius: 50%;
            position: relative; /* 让蚂蚁相对于圆形定位 */
        }

        .ant {
            display: block;
            width: 15px;
            height: 25px;
            position: absolute; /* 配合offset-path使用 */
            /* 用CSS绘制简单的蚂蚁形状(替代GIF) */
            background: #333;
            border-radius: 3px;
        }

        /* 蚂蚁的头部 */
        .ant::before {
            content: '';
            position: absolute;
            width: 8px;
            height: 8px;
            background: #333;
            border-radius: 50%;
            top: -4px;
            left: 3.5px;
        }

        /* 蚂蚁的触角 */
        .ant::after {
            content: '';
            position: absolute;
            width: 10px;
            height: 2px;
            background: #333;
            top: -8px;
            left: 2.5px;
            transform: rotate(-30deg);
        }

        /* 蚂蚁的腿部 */
        .ant span {
            position: absolute;
            width: 8px;
            height: 2px;
            background: #333;
        }

        .ant span:nth-child(1) { top: 5px; left: -6px; transform: rotate(30deg); }
        .ant span:nth-child(2) { top: 12px; left: -8px; }
        .ant span:nth-child(3) { top: 19px; left: -6px; transform: rotate(-30deg); }
        .ant span:nth-child(4) { top: 5px; right: -6px; transform: rotate(-30deg); }
        .ant span:nth-child(5) { top: 12px; right: -8px; }
        .ant span:nth-child(6) { top: 19px; right: -6px; transform: rotate(30deg); }

        /* 运动路径和动画 */
        .ant {
            offset-path: circle(540px); /* 圆形路径,半径75px(与150px直径匹配) */
            animation: walk 5ms linear infinite; /* 一圈,匀速循环 */
            transform: rotate(90deg); /* 调整蚂蚁朝向,使其沿路径正向行走 */
        }

        @keyframes walk {
            to {
                offset-distance: 100%; /* 从路径起点运动到终点 */
            }
        }
    </style>
</head>
<body>
    <div class="shape">
        <i class="ant">
            <!-- 蚂蚁的腿部(用span实现) -->
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </i>
    </div>
</body>
</html>