超简单的跳动爱心

1. css实现方式

html 复制代码
<body>
    <div class="heart"></div>
</body>
<style>
        body { 
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #ffe6f2;
            margin: 0;
        }

        .heart {
            position: relative;
            width: 100px;
            height: 90px;
            animation: heartbeat 1.2s infinite;
        }

        .heart:before,
        .heart:after {
            position: absolute;
            content: "";
            left: 50px;
            top: 0;
            width: 50px;
            height: 80px;
            background: #ff66a3;
            border-radius: 50px 50px 0 0;
            transform: rotate(-45deg);
            transform-origin: 0 100%;
        }

        .heart:after {
            left: 0;
            transform: rotate(45deg);
            transform-origin: 100% 100%;
        }

        @keyframes heartbeat {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.2);
            }

            100% {
                transform: scale(1);
            }
        }
    </style>

2. canvas实现方式

html 复制代码
<body>
<canvas id="heartCanvas" width="300" height="300"></canvas>
</body>

<style>
body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #ffe6f2;
            margin: 0;
        }
        canvas {
            border: 1px solid #ddd;
            background-color: white;
        }
</style>
javascript 复制代码
<script>
        const canvas = document.getElementById('heartCanvas');
        const ctx = canvas.getContext('2d');
        
        let scale = 1;
        let direction = 1;
        
        function drawHeart(scale) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            ctx.beginPath();
            ctx.fillStyle = '#ff66a3';
            
            // 绘制心形
            const centerX = canvas.width / 2;
            const centerY = canvas.height / 2;
            const size = 80 * scale;
            
            ctx.moveTo(centerX, centerY);
            for (let i = 0; i < Math.PI * 2; i += 0.01) {
                const x = centerX + size * (16 * Math.pow(Math.sin(i), 3)) / 16;
                const y = centerY - size * (13 * Math.cos(i) - 5 * Math.cos(2*i) - 2 * Math.cos(3*i) - Math.cos(4*i)) / 16;
                ctx.lineTo(x, y);
            }
            
            ctx.closePath();
            ctx.fill();
        }
        
        function animate() {
            scale += direction * 0.02;
            
            if (scale > 1.2) {
                direction = -1;
            } else if (scale < 1) {
                direction = 1;
            }
            
            drawHeart(scale);
            requestAnimationFrame(animate);
        }
        
        animate();
    </script>