ES6面向对象之绚丽小球
2018-11-07 本文已影响8人
前端来入坑
ES6面向对象之绚丽小球.gif
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES6面向对象之绚丽小球</title>
<style type="text/css">
body{
margin: 0 auto;
text-align: center;
}
#canvas{
margin: 10px auto;
text-align: auto;
box-shadow: 0 0 10px #000;
}
</style>
</head>
<body>
<canvas id="canvas">当前的浏览器不支持该版本</canvas>
<script type="text/javascript">
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;//x轴位置
this.y = 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();//开启上下文,保存,通用步骤
}
}
//会移动的小球的类,继承Ball的属性
class MoveBall extends Ball{
constructor(x, y, color) {
super(x, y, color)//继承之后调用父类的参数
//小球量的变化
this.dX = Newrandom(-5, 5);
this.dY = Newrandom(-5, 5);
this.dR = Newrandom(1, 3);
}
upDate() {
this.x += this.dX;
this.y += this.dY;
this.r -= this.dR;
if (this.r < 0) {
this.r = 0;
}
}
}
//实例化小球
let ballArr = [];
//监听鼠标移动事件
canvas.addEventListener('mousemove',function(e){
let ball = new MoveBall(e.offsetX, e.offsetY, randomRgbColor());
ballArr.push(ball);
});
//开启定时器
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);
function Newrandom(x,y) {
//x-y里面的随机整数获取
let a = Math.floor(Math.random()*(y-x))+x;
return a;
}
function randomRgbColor() {
//生成随机RGB颜色
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}, ${b}`;
}
</script>
</body>
</html>
ES6的继承https://www.jianshu.com/p/3d09c6fe330e
ES6面向对象之弹性小球https://www.jianshu.com/p/d5faf676f138