一个小Demo,随着鼠标的移动,会产生随机颜色的气泡。
完整代码如下(可直接复制运行):
<!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" >当前浏览器不支持此版本!</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' ;
//创建球的实体类
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();
}
}
//创建会移动的类
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' ] ;
//鼠标监听
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);
});
//创建定时器
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>
运行的效果如下: