canvas實現粒子星空連線


<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>離子星空</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#myCanvas {
background-color: black;
}
</style>
</head>

<body>
<canvas id="myCanvas"></canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
var ctx = canvas.getContext("2d");
//創建小球的構造函數
function Ball() {
this.x = randomNum(3, canvas.width - 3);
this.y = randomNum(3, canvas.height - 3);
this.r = randomNum(1, 3);
this.color = randomColor();
this.speedX = randomNum(-3, 3) * 0.2;
this.speedY = randomNum(-3, 3) * 0.2;
}
Ball.prototype = {
//繪制小球
draw: function () {
ctx.beginPath();
ctx.globalAlpha = 1;
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fill();
},
//小球移動
move: function () {
this.x += this.speedX;
this.y += this.speedY;
//為了合理性,設置極限值
if (this.x <= 3 || this.x > canvas.width - 3) {
this.speedX *= -1;
}
if (this.y <= 3 || this.y >= canvas.height - 3) {
this.speedY *= -1;
}
}
}
//存儲所有的小球
var balls = [];
//創建200個小球
for (var i = 0; i < 150; i++) {
var ball = new Ball();
balls.push(ball);
}
main();

function main() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//鼠標移動繪制線
mouseLine();
//小球與小球之間自動畫線
drawLine();
//使用關鍵幀動畫,不斷的繪制和清除
window.requestAnimationFrame(main);
}
//添加鼠標移動事件
//記錄鼠標移動時的mouseX坐標
var mouseX;
var mouseY;
canvas.onmousemove = function (e) {
var ev = event || e;
mouseX = ev.offsetX;
mouseY = ev.offsetY;
}
//判斷是否划線

function drawLine() {
for (var i = 0; i < balls.length; i++) {
balls[i].draw();
balls[i].move();
for (var j = 0; j < balls.length; j++) {
if (i != j) {
if (Math.sqrt(Math.pow((balls[i].x - balls[j].x), 2) + Math.pow((balls[i].y - balls[j].y), 2)) < 80) {
ctx.beginPath();
ctx.moveTo(balls[i].x, balls[i].y);
ctx.lineTo(balls[j].x, balls[j].y);
ctx.strokeStyle = "white";
ctx.globalAlpha = 0.2;
ctx.stroke();
}
}
}
}
}
//使用鼠標移動划線

function mouseLine() {
for (var i = 0; i < balls.length; i++) {
if (Math.sqrt(Math.pow((balls[i].x - mouseX), 2) + Math.pow((balls[i].y - mouseY), 2)) < 80) {
ctx.beginPath();
ctx.moveTo(balls[i].x, balls[i].y);
ctx.lineTo(mouseX, mouseY);
ctx.strokeStyle = "white";
ctx.globalAlpha = 0.8;
ctx.stroke();
}
}
}
//隨機函數

function randomNum(m, n) {
return Math.floor(Math.random() * (n - m + 1) + m);
}
//隨機顏色

function randomColor() {
return "rgb(" + randomNum(0, 255) + "," + randomNum(0, 255) + "," + randomNum(0, 255) + ")";
}
</script>

</html>

---------------------
作者:motokay
來源:CSDN
原文:https://blog.csdn.net/qq_37506861/article/details/77510847
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM