html粒子连接,HTML5/Canvas 粒子连接图

这篇博客介绍了如何使用JavaScript和Canvas API创建一个粒子系统。通过定义Particle类,设置粒子的位置、速度和颜色,然后在画布上绘制和更新粒子,实现了粒子之间的碰撞效果。代码中运用了Babel和CoffeeScript,展示了前端开发中的动态视觉效果技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JavaScript

语言:

JaveScriptBabelCoffeeScript

确定

var canvas = document.getElementById('canvas'),

ctx = canvas.getContext('2d'),

W = canvas.width = window.innerWidth,

H = canvas.height = window.innerHeight,

particles = [],

numParticles = W / 4;

function Particle() {

this.x = Math.random() * W;

this.y = Math.random() * H;

this.vx = Math.random() * 5 + 0.05;

this.vy = Math.random() * 5 + 0.05;

this.radius = Math.random() * 10 + 0.5;

this.color = 'orange';

}

Particle.prototype.draw = function() {

ctx.beginPath();

ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);

ctx.fillStyle = this.color;

ctx.fill();

};

Particle.prototype.update = function() {

for (var i = 0; i < particles.length; i++) {

var dx = particles[i].x - this.x,

dy = particles[i].y - this.y,

dist = Math.sqrt(dx * dx + dy * dy);

if (dist < particles[i].radius + (this.radius + 50)) {

ctx.moveTo(this.x, this.y);

ctx.lineTo(particles[i].x, particles[i].y);

ctx.strokeStyle = 'orange';

ctx.stroke();

}

}

this.x += this.vx;

this.y += this.vy;

if (this.x - this.radius / 2 > W) {

this.x = -this.radius / 2;

this.reset();

} else if (this.x + this.radius / 2 < 0) {

this.x = W + this.radius / 2;

this.reset();

}

if (this.y - this.radius / 2 > H) {

this.y = -this.radius / 2;

this.reset();

} else if (this.y + this.radius / 2 < 0) {

this.y = H + this.radius / 2;

this.reset();

}

};

for (var i = 0; i < numParticles; i++) {

particles.push(new Particle());

}

Particle.prototype.reset = function() {

this.vx = Math.random() * 5 + 0.05;

this.vy = Math.random() * 5 + 0.05;

};

;

(function drawFrame() {

requestAnimationFrame(drawFrame);

ctx.clearRect(0, 0, W, H);

for (var i = 0; i < particles.length; i++) {

particles[i].draw();

particles[i].update();

}

})();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值