canvas实现撒彩带
时间: 2023-12-09 11:37:07 浏览: 172
ec-canvas 实现echart图表显示
以下是使用canvas实现撒彩带的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8 <title>Canvas实现撒彩带</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
background-color: #000;
}
canvas {
display: block;
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="mycanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
var particles = [];
var particleCount = 100;
var particleSpeed = 2;
var particleSize = 3;
var colors = ['#bf3242', '#ebebeb', '#ffffff', '#d9d9d9'];
function Particle() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = ((Math.random() - 0.5) * particleSpeed);
this.vy = ((Math.random() - 0.5) * particleSpeed);
this.size = Math.random() * particleSize;
this.color = colors[Math.floor(Math.random() * colors.length)]; }
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
function createParticles() {
for (var i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
}
function drawParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].x += particles[i].vx;
particles[i].y += particles[i].vy;
if (particles[i].x > canvas.width) {
particles[i].x = 0;
}
if (particles[i].x < 0) {
particles[i].x = canvas.width;
}
if (particles[i].y > canvas.height) {
particles[i].y = 0;
}
if (particles[i].y < 0) {
particles[i].y = canvas.height;
}
particles[i].draw();
}
requestAnimationFrame(drawParticles);
}
createParticles();
drawParticles();
</script>
</body>
</html>
```
阅读全文