<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>炫彩小球demo</title>
</head>
<body>
<canvas id='myCanvas'></canvas>
<script>
let myCanvas = document.getElementById('myCanvas')
let ctx = myCanvas.getContext('2d')
console.log(ctx)
function Ball(x, y, r){
this.x = x
this.y = y
this.r = r
this.color = getRandom()
this.dx = parseInt(Math.random() * 10) - 5
this.dy = parseInt(Math.random() * 10) - 5
ballArr.push(this)
}
Ball.prototype.render = function(){
ctx.beginPath()
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
ctx.fillStyle = this.color
ctx.fill()
}
Ball.prototype.update = function(){
this.x += this.dx
this.y += this.dy
this.r -= 0.1
if(this.r < 0){
this.remove()
}
}
Ball.prototype.remove = function(){
for(var i = 0; i < ballArr.length; i++){
if(ballArr[i] === this){
ballArr.splice(i, 1)
}
}
}
function getRandom(){
var allType = '0,1,2,3,4,5,6,7,8,a,b,c,d,e,f'
var allTypeArr = allType.split(',')
var color = '#'
for(let i = 0; i < 6; i++){
var random = parseInt(Math.random() * allTypeArr.length)
color += allTypeArr[random]
}
return color
}
var ballArr = []
setInterval(function(){
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
for(let i = 0; i < ballArr.length; i++){
ballArr[i].update()
if(ballArr[i]){
ballArr[i].render()
}
}
}, 20)
myCanvas.addEventListener('mousemove', function(e){
new Ball(e.offsetX, e.offsetY, parseInt(Math.random() * 20))
console.log(ballArr)
})
</script>
</body>
</html>
炫彩小球demo
最新推荐文章于 2022-09-28 11:42:22 发布