使用canvas制作一个万圣节的简单动画

要制作一个简单的万圣节动画,我们可以使用HTML的<canvas>元素和JavaScript。以下是一个示例,它显示了一个飘动的南瓜灯(Jack-o'-lantern)动画:

  1. HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>万圣节动画</title>
    <style>
        canvas {
            border: 1px solid black;
            background-color: #222;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="800" height="600"></canvas>
    <script src="script.js"></script>
</body>
</html>
  1. JavaScript (script.js 文件):
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

const lanternRadius = 50;
let lanternX = canvas.width / 2;
let lanternY = canvas.height - 100;
const lanternSpeed = 2;
let lanternDirection = 1; // 1 for right, -1 for left

function drawLantern() {
    ctx.beginPath();
    ctx.arc(lanternX, lanternY, lanternRadius, 0, Math.PI * 2);
    ctx.fillStyle = 'orange';
    ctx.fill();
    ctx.strokeStyle = 'black';
    ctx.stroke();

    // Draw the face
    ctx.beginPath();
    ctx.arc(lanternX - 15, lanternY - 20, 10, 0, Math.PI * 2); // Left eye
    ctx.arc(lanternX + 15, lanternY - 20, 10, 0, Math.PI * 2); // Right eye
    ctx.arc(lanternX, lanternY - 10, 20, 0, Math.PI); // Mouth
    ctx.stroke();
}

function clearCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function animate() {
    clearCanvas();
    drawLantern();
    lanternX += lanternSpeed * lanternDirection;
    if (lanternX + lanternRadius > canvas.width || lanternX - lanternRadius < 0) {
        lanternDirection *= -1; // Change direction when hitting the edges
    }
    requestAnimationFrame(animate); // Loop the animation
}

animate(); // Start the animation

这个简单的动画显示了一个在屏幕底部左右飘动的南瓜灯。你可以根据需要进一步定制它,例如添加更多的万圣节元素、改变颜色或速度等。

posted @ 2024-12-29 09:43  王铁柱6  阅读(3)  评论(0编辑  收藏  举报