canvas 实现动态背景图

在这里插入图片描述
代码

<template>
  <canvas id="background"></canvas>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
type dot = {
  x: number
  y: number
  xa: number
  ya: number
  color: string
  radius: number
}

function getRandomNumber(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

function getRandomColor() {
  let a = Math.random() * 0.8 + 0.1
  let r = 255
  let color = `rgba(${r}, ${r}, ${r}55, ${a})`
  return color
}

onMounted(() => {
  let canvas = document.getElementById('background') as HTMLCanvasElement
  let ctx = canvas.getContext('2d') as CanvasRenderingContext2D

  canvas.width = canvas.clientWidth
  canvas.height = canvas.clientHeight

  const dots: dot[] = []
  for (let i = 0; i < 500; i++) {
    let x = Math.random() * canvas.width
    let y = Math.random() * canvas.height * 0.6
    let xa = 0
    let ya = Math.random() * 2 - 1
    dots.push({
      x: x,
      y: y,
      xa: xa,
      ya: ya / 10,
      color: getRandomColor(),
      radius: getRandomNumber(1, 3)
    })
  }
  const animate = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    dots.forEach((dot) => {
      dot.y += dot.ya
      dot.xa *= dot.x > canvas.width || dot.x < 0 ? -1 : 1
      dot.ya *= dot.y > canvas.height || dot.y < 0 ? -1 : 1

      ctx.fillStyle = dot.color

      ctx.beginPath()
      ctx.arc(dot.x - 0.5, dot.y - 0.5, dot.radius, 0, Math.PI * 2)
      ctx.fill()
      ctx.closePath()
    })

    window.requestAnimationFrame(animate)
  }
  animate()
})
</script>

<style lang="less" scoped>
#background {
  width: 100%;
  height: 100%;
}
</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值