记录js编写随机改变的渐变背景

1,936 阅读1分钟

前言

记录随机改变的渐变色背景,只需要全部代码的可以直接到文章最底下。

随机渐变背景

每隔一段时间就会自动生成一个方向随机,颜色随机的渐变色背景

uTools_1638495960918.png

uTools_1638495946916.png

如何制作

  1. 首先这个背景是全都由 js 生成的,我们只需要创建一个 div 元素,然后将它设定为 fixed ,层级设定的低一点,在添加到 body 底下
const el = document.createElement('div')
 el.style.cssText = '
     position:fixed;
     top:0;
     left:0;
     right:0;
     bottom:0;
     z-index:-3;
     transition: 1s linear;'
el.style.backgroundImage =
   `linear-gradient(${deg}deg, ${randomColor()} 0%, ${randomColor()} 100%)`
document.body.appendChild(el)
  1. 然后这个背景色和随机数分别是一个随机生成颜色和随机数函数生成的
  • 随机数函数:只需要传入一个最大值,返回一个0~最大值的随机数
 function randomInt(max) {
    return Math.floor(Math.random() * max)
}
  • 背景色随机生成函数:基于随机函数生成一个随机的背景色,具体参数可以自己调整
 function randomColor() {
    const r = randomInt(255)
    const g = randomInt(255)
    const b = randomInt(255)
    const c = `#${r.toString(16)}${g.toString(16)}${b.toString(16)}000`
    return c.slice(0, 7)
}
  1. 这些东西整合起来,就能实现一个随机生成的背景色,接下去就是背景隔一段时间自己改变,这就要通过定时器来完成
function setBg() {
    const randomBg =
        `linear-gradient(${deg}deg, ${randomColor()} 0%, ${randomColor()} 100%)`
    el.style.opacity = '.3'
    setTimeout(() => {
        el.style.backgroundImage = randomBg
        el.style.opacity = '1'
    }, 1000)
}
randomTimer = setInterval(setBg, 10000)

这样就完成了一个动态的渐变背景,下面附带完整的代码:

let randomTimer

function randomColor() {
    const r = randomInt(255)
    const g = randomInt(255)
    const b = randomInt(255)
    const c = `#${r.toString(16)}${g.toString(16)}${b.toString(16)}000`
    return c.slice(0, 7)
}

function randomInt(max) {
    return Math.floor(Math.random() * max)
}

function randomBgImg() {
    clearInterval(randomTimer)
    const el = document.createElement('div')
    const deg = randomInt(360)
    el.id = 'random-light-bg'
    el.style.cssText = '
    position:fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index:-99;
    transition: 1s linear;'
    el.style.backgroundImage =
        `linear-gradient(${deg}deg, ${randomColor()} 0%, ${randomColor()} 100%)`
    document.body.appendChild(el)

    function setBg() {
        const randomBg =
            `linear-gradient(${deg}deg, ${randomColor()} 0%, ${randomColor()} 100%)`
        el.style.opacity = '.3'
        setTimeout(() => {
            el.style.backgroundImage = randomBg
            el.style.opacity = '1'
        }, 1000)
    }

    randomTimer = setInterval(setBg, 10000)
}
randomBgImg();

总结

本文使用一个github项目里面的背景色设计,项目地址: github.com/xjh22222228…