一個小Demo,隨著鼠標(biāo)的移動哮洽,會產(chǎn)生隨機顏色的氣泡填渠。
完整代碼如下(可直接復(fù)制運行):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
#canvas{
margin-left: 150px ;
box-shadow: 0 0 10px #000;
}
</style>
<body>
<canvas id="canvas" >當(dāng)前瀏覽器不支持此版本!</canvas>
</body>
<script>"js/underscore-min.js"</script>
<script>
//獲取畫布
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 1000 ;
canvas.height = 600 ;
canvas.style.backgroundColor = '#000' ;
//創(chuàng)建球的實體類
class Ball{
constructor (x , y , color){
this.x = x ;
this.y = y ;
this.color = color;
this.r = 40 ;
}
//繪制球
render () {
ctx.save ();
ctx.beginPath();
ctx.arc(this.x , this.y , this.r , 0 , Math.PI*2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
//創(chuàng)建會移動的類
class MoveBall extends Ball{
constructor(x , y , color , word){
super(x, y , color );
this.dx = Math.floor(Math.random()*4) ;
this.dy = Math.floor(Math.random()*4) ;
this.dr = 1 + Math.floor(Math.random()*4);
}
update(){
this.x += this.dx ;
this.y += this.dy ;
this.r -= this.dr ;
if(this.r < 0 ){
this.r = 0 ;
}
}
}
//實例化小球
let ballArr = [] ;
let colorArr = ['red' , 'blue' , 'green' , 'yellow' , 'orange' ] ;
//鼠標(biāo)監(jiān)聽
canvas.addEventListener('mousemove' , function(e){
let index = Math.floor(Math.random()*colorArr.length);
ballArr.push(new MoveBall(e.offsetX , e.offsetY , colorArr[index]));
console.log(ballArr);
});
//創(chuàng)建定時器
setInterval(function(){
ctx.clearRect(0 , 0 , canvas.width,canvas.height);
//遍歷小球
for(let i = 0 ; i<ballArr.length ; i++){
ballArr[i].render();
ballArr[i].update();
}
} , 50);
</script>
</html>
運行的效果如下: