返回

流动的夜空,中秋许愿之旅

前端

中秋之夜,星月交辉

中秋佳节,皓月当空,繁星点点,交织成一幅流动的夜空画卷。canvas的出现,让我们能够用代码描绘这幅美景,让它在屏幕上栩栩如生。

首先,让我们创建我们的画布:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

接下来,我们来绘制那轮皎洁的明月:

ctx.beginPath();
ctx.fillStyle = "#FFFFF0";
ctx.arc(canvas.width / 2, canvas.height / 2, 100, 0, 2 * Math.PI);
ctx.fill();

点缀繁星,闪烁夜空

繁星点点,为夜空增添了无限的生机。让我们用canvas来描绘这些闪亮的星星:

for (let i = 0; i < 100; i++) {
  ctx.fillStyle = "#FFFFFF";
  ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 2, 2);
}

流星划过,许下心愿

流星划过天际,带来了一丝转瞬即逝的美丽和许愿的契机。我们使用canvas来模拟流星的轨迹:

for (let i = 0; i < 10; i++) {
  ctx.strokeStyle = "#FFFFFF";
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
  ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
  ctx.stroke();
}

交互体验,圆梦寄语

为了让我们的许愿之旅更加互动,我们可以添加一个按钮,让用户点击许愿:

document.getElementById("btnWish").addEventListener("click", function() {
  ctx.font = "30px Arial";
  ctx.fillStyle = "#FFFFFF";
  ctx.fillText("许愿成功!", canvas.width / 2 - 100, canvas.height / 2);
});

结语

在中秋佳节的夜晚,我们用canvas描绘了一幅流动的夜空,点缀繁星,流星划过,寄托美好愿望。通过详细的步骤和示例代码,本文带你领略了canvas的强大魅力,让你体验中秋佳节的独特浪漫。现在,拿起你的键盘,用canvas编织你自己的中秋许愿之旅吧!