<!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>Document</title>
<style>
canvas {
border: 1px solid #444;
/* margin: 0 auto; */
display: block;
}
</style>
</head>
<body>
<canvas id="canvas" width="500px" height="500px"
>浏览器版本过低,请升级最新版本谷歌浏览器(只有低版本浏览器才会显示标签内的文字)</canvas
>
</body>
<script>
//获取canvas画布
var canvas = document.querySelector('#canvas');
// //获取上下文
var ctx = canvas.getContext('2d');
var w = 500;
var h = 500;
//第一步:创建小球类
var text = '12';
function Ball(x, y) {
this.x = x;
this.y = y;
this.r = 30;
this.color = random_color();
}
//定义小球显示方法
Ball.prototype.show = function () {
this.r--; //半径越来越小
drawCircle(this.x, this.y, this.r, this.color);
};
//鼠标移动事件,创建并加入小球数组
var ballArr = [];
window.onmousemove = function (e) {
var ball = new Ball(e.x, e.y);
ballArr.push(ball);
ball.show();
};
//让创建好的逐渐变小直至删除
setInterval(() => {
ctx.clearRect(0, 0, w, h); //先清除画布
for (var i = 0; i < ballArr.length; i++) {
var ball = ballArr[i];
if (ball.r <= 0) {
ballArr.splice(i, 1);
} else {
ball.show();
}
}
}, 20);
//封装画直线
function drawLine(x1, y1, x2, y2, color, width) {
//开启一条路径
ctx.beginPath();
// //确定起始点
ctx.moveTo(x1, y1);
// //到哪里结束
ctx.lineTo(x2, y2);
// //关闭路径
ctx.closePath();
//设置颜色
ctx.strokeStyle = color;
//设置线宽
ctx.lineWidth = width;
//着色(如果要设置颜色和线宽,务必在着色之前设置)
ctx.stroke();
}
//封装画实心圆
function drawCircle(x, y, r, color, text) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.fillStyle = color;
ctx.fill();
}
//封装产生随机数
function random_num(num) {
return parseInt(Math.random() * num);
}
//生成rgb随机颜色
function random_color() {
var rgb =
'rgb(' +
Math.floor(Math.random() * 255) +
',' +
Math.floor(Math.random() * 255) +
',' +
Math.floor(Math.random() * 255) +
')';
console.log(rgb);
return rgb;
}
</script>
</html>