<style>
*{margin: 0;padding: 0;}
canvas{ display: block;margin: 10px auto;border: 1px solid #333;}
</style>
<body>
<canvas id="mycanvas"></canvas>
<script>
var canvas = document.getElementById("mycanvas");
//上下文
var ctx = canvas.getContext("2d");
//console.log(ctx)
canvas.width = document.documentElement.clientWidth - 30;
canvas.height = document.documentElement.clientHeight - 30;
//console.log( canvas.width, canvas.height)
//小球类
function Ball(){
//半径
this.r = 10;
//圆心
do{
this.x = parseInt(Math.random() * canvas.width);
this.y = parseInt(Math.random() * canvas.height);
}while(this.x < this.r || this.x > canvas.width - this.r || this.y< this.r || this.y > canvas.height - this.r)
//速度 -5到4 不同方向移动不能为0
do{
this.dx = parseInt(Math.random() * 10) - 5;
this.dy = parseInt(Math.random() * 10) - 5;
}while(this.dx ==0 && this.dy ==0)
//小球颜色
this.color = "gray";
//维护小球的数组
ballArr.push(this);
//记录小球在数组中的位置 避免互相连线
this.index = ballArr.length-1;
}
//渲染小球
Ball.prototype.render = function(){
//console.log(this.index);
//画圆
ctx.beginPath();
//透明度
ctx.globalAlpha = 1;
ctx.arc(this.x,this.y,this.r,0,Math.PI * 2,false);
ctx.fillStyle= this.color;
ctx.fill();
for(var i=this.index;i<ballArr.length;i++){
if(Math.abs(ballArr[i].x - this.x) < 150 && Math.abs(ballArr[i].y - this.y) < 150){
ctx.beginPath();
// 线的透明度,根据当前的两个已经连线的小球的距离进行线的透明度设置
//Math.pow()返回 x 的 y 次幂的值。
//Math.sqrt函数返回一个数的平方根
ctx.globalAlpha = 10 / Math.sqrt(Math.pow(ballArr[i].x - this.x, 2) + Math.pow(ballArr[i].y - this.y, 2))
ctx.moveTo(this.x,this.y);
ctx.lineTo(ballArr[i].x,ballArr[i].y);
ctx.strokeStyle = "#000";
ctx.closePath();
ctx.stroke();
}
}
}
//小球运动
Ball.prototype.update = function(){
//console.log(ballArr)
this.x += this.dx;
this.y += this.dy;
//如果超出画布,向相反的方向移动
if(this.x < this.r || this.x > canvas.width-this.r){
this.dx = -this.dx;
}
if(this.y < this.r || this.y > canvas.height - this.r){
this.dy = -this.dy;
}
}
//将小球维护到数组中
var ballArr = [];
//创建小球
for(var i=0;i<50;i++){
new Ball();
}
//定时器渲染更新小球
setInterval(() => {
//清除画布
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<ballArr.length;i++){
ballArr[i].render();
ballArr[i].update();
}
}, 20);
</script>
</body>
</html>
canvas 中文文档