canvas连线特效

时间:2022-06-16 02:30:40
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
#myCanvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var myCanvas = document.getElementById("myCanvas");
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
myCanvas.width = width;
myCanvas.height = height; var ctx = myCanvas.getContext("2d");
ctx.fillStyle = "white";
ctx.strokeStyle = "rgba(255, 255, 255, .3)";
function Star(ctx, x, y, r){
this.ctx = ctx;
this.x = x;
this.y = y;
this.r = r;
this.x_speed = (parseInt(Math.random() * 3) + 1) * Math.pow(-1, parseInt(Math.random() * 10) + 1) / 5;
this.y_speed = (parseInt(Math.random() * 3) + 1) * Math.pow(-1, parseInt(Math.random() * 10) + 1) / 5;
}
Star.prototype.render = function(){
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
this.ctx.closePath();
this.ctx.fill();
}
Star.prototype.move = function(){
this.x -= this.x_speed;
this.y -= this.y_speed;
}
Star.prototype.changeX = function(){
this.x_speed = -this.x_speed;
}
Star.prototype.changeY = function(){
this.y_speed = -this.y_speed;
} var mouse_star = new Star(ctx, 0, 0, 1);
var arr = [];
document.onmousemove = function(e){
mouse_star.x = e.clientX;
mouse_star.y = e.clientY;
} document.onclick = function(e){
for (var i = 0; i < 5; i++) {
arr.push(new Star(ctx, e.clientX, e.clientY, 1));
};
setTimeout(function(){
for (var i = 0; i < 5; i++) {
arr.pop();
};
},3000)
} for (var i = 0; i < 100; i++) {
arr.push(new Star(ctx, Math.random() * width, Math.random() * height, 1));
};
setInterval(function(){
ctx.clearRect(0, 0, width, height);
mouse_star.render(); arr.forEach(function(value, index){
value.move();
if (value.x < 0 || value.x > width ) {
value.changeX();
};
if (value.y < 0 || value.y > height) {
value.changeY();
};
value.render();
}); arr.forEach(function(value, index){
for (var i = index; i < arr.length; i++){
if (Math.abs(value.x-arr[i].x) < 50 && Math.abs(value.y - arr[i].y) < 50 ) {
line(value.x, value.y, arr[i].x, arr[i].y);
};
}
if(Math.abs(value.x - mouse_star.x) < 150 && Math.abs(value.y - mouse_star.y) < 150) {
line(value.x, value.y, mouse_star.x, mouse_star.y);
}
})
}, 20);
   
function line(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.closePath();
ctx.stroke();
}
</script>
</body>
</html>