canvas畫布小球動(dòng)畫
style樣式
#canvas{
box-shadow:0 0 10px #000;
}
body布局
<canvas id="canvas" width="" height="">
? <span id='sp'>
? ? ? 請(qǐng)升級(jí)瀏覽器? 以顯示內(nèi)容
</canvas>
script代碼
//生成一個(gè)隨機(jī)數(shù)
let newMath = (x,y) => {
let num=y-x
return Math.floor(Math.random()*num+x)
}
//1.生成一個(gè)隨即色值
let randomRgbColor = () => {
//獲取256以內(nèi)的隨機(jī)數(shù)
? let r=Math.floor(Math.random()*256)
let g=Math.floor(Math.random()*256)
let b=Math.floor(Math.random()*256)
return `rgba(${r},${g},$,.5)`
}
//2.獲取畫布
const canvas = document.getElementById('canvas')
//獲取畫布的上下文
const ctx = canvas.getContext('2d')
canvas.width ='1000'
canvas.height ='600'
canvas.style.background ="#000"
//3.創(chuàng)建小球的類
class Ball{
//constructor()是每個(gè)類里必須要有的方法,如果沒寫柜思,也會(huì)有一個(gè)默認(rèn)的出現(xiàn)
? //這個(gè)方法是類的構(gòu)造函數(shù)糯崎,一些屬性的存放在這里
? constructor(x,y,color){
this.x = x
this.y = y
this.color = color
this.r =40
? }
//根據(jù)屬性的值,來制作小球
? render(){
//這里保存的是沒有任何設(shè)置的初始狀態(tài)
? ? ? ctx.save()//保存狀態(tài)
? ? ? ctx.beginPath()//開始繪制
? ? ? ctx.arc(this.x,this.y,this.r,0,Math.PI*2)
ctx.fillStyle =this.color
? ? ? ctx.fill()
//加載初始狀態(tài)
? ? ? //這里的作用是 重置所有設(shè)置? 避免下一次繪制出現(xiàn)錯(cuò)誤
? ? ? ctx.restore()
}
}
//4.讓小球移動(dòng)起來
? //讓MoveBall 繼承Ball
//extends :繼承的關(guān)鍵字
class MoveBallextends Ball{
constructor(x,y,color){
//super關(guān)鍵字狠角,在繼承中必須使用的關(guān)鍵字
? ? ? //用來代表父類的構(gòu)造方法
? ? ? super(x,y,color)
this.dx =newMath(-5,5)
this.dy =newMath(-5,5)
this.dr =newMath(1,3)
}
//更新數(shù)據(jù)
? update(){
//this.x:當(dāng)前的位置
? ? ? //this.dx:每次移動(dòng)的距離
? ? ? this.x +=this.dx
? ? ? this.y +=this.dy
? ? ? this.r -=this.dr
? ? ? if(this.r<0){
this.r=0
? ? ? }
}
}
//5.儲(chǔ)存變化的小球
let barArr = []
//6.監(jiān)聽鼠標(biāo)的移動(dòng)事件
canvas.addEventListener("mousemove",function(ev){
var ev = ev || window.ev
? //? ? ? ? ? ? ? x? ? ? ? y? ? ? ? ? ? ? color
? barArr.push(new MoveBall(ev.offsetX,ev.offsetY,randomRgbColor()))
})
//7.開始定時(shí)器,繪制動(dòng)畫
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
for(let i =0 ; i
barArr[i].render()
console.log(barArr[i])
barArr[i].update()
}
},50)