可以直接在浏览器控制台运行的js生成雪花的代码
时间: 2023-03-24 17:04:14 浏览: 56
可以尝试以下代码:
```
var canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var flakes = [];
function Flake() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = Math.random() * 3 + 2;
this.speed = Math.random() * 1 + .5;
this.opacity = Math.random() * .5 + .5;
}
Flake.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, , Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, ' + this.opacity + ')';
ctx.fill();
};
Flake.prototype.update = function() {
this.y += this.speed;
if (this.y > canvas.height) {
this.y = -this.radius;
this.x = Math.random() * canvas.width;
}
};
for (var i = ; i < 100; i++) {
flakes.push(new Flake());
}
function animate() {
ctx.clearRect(, , canvas.width, canvas.height);
for (var i = ; i < flakes.length; i++) {
flakes[i].draw();
flakes[i].update();
}
requestAnimationFrame(animate);
}
animate();
```
这段代码可以在浏览器控制台中运行,生成雪花效果。