<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
let c = document.getElementById('myCanvas');
c.width = window.innerWidth;
c.height = window.innerHeight;
c.style.backgroundColor = '#000';
let ctx = c.getContext('2d')
let dotArray = []
random(dotArray, 30, 3)
draw()
//生成随机点坐标与随机方向
function random(arr, sum, v) {
for (let i = 0; i < sum; i++) {
let x1 = Math.random() * window.innerWidth;
let y1 = Math.random() * window.innerHeight;
let x2 = Math.random() * v - v / 2;
let y2 = Math.random() * v - v / 2;
arr.push({ coordinate: [x1, y1], direction: [x2, y2] })
}
}
//绘制动画
function draw() {
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight); //清空所有的内容
dot(dotArray, 5) //画点
line(dotArray, 2, 200) //连线
requestAnimationFrame(draw); //定时器动画
}
function dot(arr, r) {
arr.map((item, index, array) => {
let x = item.coordinate[0] + item.direction[0];
let y = item.coordinate[1] + item.direction[1];
array[index].coordinate[0] = x;
array[index].coordinate[1] = y;
if (x < 0 || x > window.innerWidth) {
array[index].direction[0] = -array[index].direction[0];
}
if (y < 0 || y > window.innerHeight) {
array[index].direction[1] = -array[index].direction[1];
}
})
arr.map((item) => {
ctx.beginPath()
ctx.fillStyle = 'rgba(255,255,255,1)'
ctx.arc(item.coordinate[0], item.coordinate[1], r, 0, 2 * Math.PI)
ctx.fill()
ctx.closePath()
})
}
//连线
function line(arr, lineWidth, distance) {
arr.map(item => {
arr.map(item2 => {
let x1 = item.coordinate[0]
let y1 = item.coordinate[1]
let x2 = item2.coordinate[0]
let y2 = item2.coordinate[1]
let d = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
if (d < distance) {
ctx.beginPath()
ctx.strokeStyle = 'rgba(255,255,255,' + (distance - d) / distance + ')'
ctx.lineWidth = lineWidth
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
ctx.closePath()
}
})
})
}
</script>
</body>
</html>
canvas动画-随机弹珠
最新推荐文章于 2024-05-14 16:27:26 发布