效果图
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
canvas {
border: 1px solid pink;
}
</style>
<body>
<canvas></canvas>
</body>
<script>
/** @type {HTMLCanvasElement} */
let canvas = document.querySelector('canvas')
canvas.width = window.innerWidth - 30
canvas.height = window.innerHeight - 30
let ctx = canvas.getContext('2d')
function randommunber(first, last) {
let number = Math.floor(Math.random() * (first - last) + last)
return number
}
function Ball(x, y, radius, color, lasttime) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.tempcos = randommunber(0, 2 * Math.PI)
this.tempsd = 0.05
this.draw = function (lasttime) {
ctx.beginPath()
ctx.lineWidth = this.radius
ctx.strokeStyle = '' + color
ctx.moveTo(lasttime.x, lasttime.y)
ctx.lineTo(this.x, this.y)
ctx.stroke()
}
this.upload = function () {
console.log(this.tempcos)
let lasttime = {
x: this.x,
y: this.y
}
this.x = canvas.width / 2 + Math.cos(this.tempcos) * 30
this.y = canvas.width / 2 + Math.sin(this.tempcos) * 30
this.tempcos += this.tempsd
this.draw(lasttime)
}
}
let temparray
function init() {
temparray = []
for (let i = 0; i < 10; i++) {
let x = canvas.width / 2
let y = canvas.width / 2
let radius = 3
let r = Math.random() * 255
let g = Math.random() * 255
let b = Math.random() * 255
color = `rgb(${r},${g},${b})`
temparray.push(new Ball(x, y, radius, color))
}
}
function arimate() {
requestAnimationFrame(arimate)
ctx.fillStyle = 'rgba(255,255,255,0.1)'
ctx.fillRect(0, 0, canvas.width, canvas.height)
for (let b of temparray) {
b.upload()
}
}
init()
arimate()
</script>
</html>