返回

随机灵动 —— JS 实现动态渐变背景

前端

前言

背景是网页的重要组成部分,它可以为网站或应用程序营造氛围,也能传递网站的风格和理念。传统的背景通常是单一的颜色或图像,而动态渐变背景则可以带来更具活力的视觉效果,让网站或应用程序更具吸引力。

实现随机灵动的渐变背景

1. HTML 结构

首先,我们需要创建一个 HTML 结构来容纳我们的 Canvas 元素。

<!DOCTYPE html>
<html>
<head>
  
</head>
<body>
  <canvas id="canvas" width="100%" height="100%"></canvas>

  <script src="script.js"></script>
</body>
</html>

2. JavaScript 代码

接下来,我们使用 JavaScript 来操纵 Canvas 元素,实现动态渐变背景。

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

// 设置画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 创建渐变
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);

// 随机生成两种颜色
const color1 = randomColor();
const color2 = randomColor();

// 将颜色添加到渐变中
gradient.addColorStop(0, color1);
gradient.addColorStop(1, color2);

// 设置渐变为画布的填充样式
ctx.fillStyle = gradient;

// 填充画布
ctx.fillRect(0, 0, canvas.width, canvas.height);

// 随机改变渐变颜色
setInterval(() => {
  // 随机生成两种颜色
  const color1 = randomColor();
  const color2 = randomColor();

  // 将颜色添加到渐变中
  gradient.addColorStop(0, color1);
  gradient.addColorStop(1, color2);

  // 填充画布
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}, 5000);

// 随机颜色函数
function randomColor() {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r}, ${g}, ${b})`;
}

3. 完整代码

<!DOCTYPE html>
<html>
<head>
  
</head>
<body>
  <canvas id="canvas" width="100%" height="100%"></canvas>

  <script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // 设置画布大小
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // 创建渐变
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);

    // 随机生成两种颜色
    const color1 = randomColor();
    const color2 = randomColor();

    // 将颜色添加到渐变中
    gradient.addColorStop(0, color1);
    gradient.addColorStop(1, color2);

    // 设置渐变为画布的填充样式
    ctx.fillStyle = gradient;

    // 填充画布
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 随机改变渐变颜色
    setInterval(() => {
      // 随机生成两种颜色
      const color1 = randomColor();
      const color2 = randomColor();

      // 将颜色添加到渐变中
      gradient.addColorStop(0, color1);
      gradient.addColorStop(1, color2);

      // 填充画布
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    }, 5000);

    // 随机颜色函数
    function randomColor() {
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      return `rgb(${r}, ${g}, ${b})`;
    }
  </script>
</body>
</html>

结语

通过本文,您已经学会了如何使用 JavaScript 和 Canvas API 实现随机灵动的渐变背景。您可以根据自己的需要调整代码,创造出更多有趣的效果。