用html+js实现代码背景墙特效【建议收藏】

在csdn里面,有些博主的主页非常的帅,就是代码从上往下掉的特效,那么这种效果我们作为程序员该如何去写出来呢,不用担心,这篇博客就分享如何创建一个代码背景墙;

1、效果展示

2、代码分享

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>bg code</title>
</head>

<body style="margin: 0">
  <canvas id="cvs" style="background-color: #000;"></canvas>
</body>
<script>
  const cvs = document.querySelector('#cvs')
  const { clientWidth: width, clientHeight: height } = document.documentElement
  cvs.width = width
  cvs.height = height
  const ctx = cvs.getContext('2d')
  const text = 'abcdefghijklmnopqrstuvwxyz'
  ctx.font = '14px 微软雅黑'
  const bl = 20
  const startRates = {}
  const rates = {}
  const endRates = {}
  const textObj = {}
  const animate = () => {
    ctx.clearRect(0, 0, width, height)
    for (let i = 0; i < width; i += bl) {
      ctx.beginPath()
      const gradient = ctx.createLinearGradient(0, 0, 0, height)
      const s1 = 0.2 * Math.random()
      const s2 = 0.8 * Math.random() + 0.2
      const step = 0.02 * Math.random()
      rates[i] = rates[i] || -s1
      endRates[i] = endRates[i] || 0
      startRates[i] = startRates[i] || -s2
      gradient.addColorStop(0, '#000000')
      gradient.addColorStop(startRates[i] < 0 ? 0 : startRates[i], '#000000')
      gradient.addColorStop(rates[i] < 0 ? 0 : rates[i], '#0ee30e')
      gradient.addColorStop(endRates[i], '#000000')
      gradient.addColorStop(1, '#000000')
      ctx.fillStyle = gradient
      for (let j = 0; j < height; j += bl) {
        textObj[i + '-' + j] = textObj[i + '-' + j] || text[parseInt(Math.random() * text.length)]
        ctx.fillText(textObj[i + '-' + j], i, j)
      }
      rates[i] += step
      endRates[i] += step
      startRates[i] += step
      if (startRates[i] > 1) {
        startRates[i] = -s2
      }
      if (rates[i] > 1) {
        if (startRates[i] === -s2) {
          rates[i] = -s1
        } else {
          rates[i] = 1
        }
      }
      if (endRates[i] > 1) {
        if (rates[i] === -s1 && startRates[i] === -s2) {
          endRates[i] = step
        } else {
          endRates[i] = 1
        }
      }
    }
    requestAnimationFrame(animate)
  }
  animate()
</script>

</html>

 

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值