html部分
<canvas id="myCanvas" style="width:100%; height: 100%;background='rgba(0,0,0,0)'"></canvas>
方法部分
<script lang="renderjs" module="myCanvas">
console.log('进来了');
export default {
mounted (){
const canvas = document.getElementById("myCanvas").childNodes[0];
// const canvas = document.getElementsByTagName('canvas')[0];
// console.log(canvas2);
// console.log(myClassElements[0]);
const ctx = canvas.getContext("2d");
console.log(ctx,'xxxxxxx');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// console.log(canvas.width,canvas.height);
// 粒子构造函数
function Particle() {
this.x = Math.random() * canvas.width; // x坐标
this.y = Math.random() * canvas.height; // y坐标
this.vx = (Math.random() - 0.5) * 2; // x轴方向速度
this.vy = (Math.random() - 0.5) * 2; // y轴方向速度
this.radius = Math.random() * 3; // 粒子大小
this.opacity = Math.random(); // 粒子透明度
}
// 绘制粒子
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255,255,255, ${this.opacity})`;
ctx.fill();
}
const particles = []; // 粒子集合
const particleNum = 200; // 粒子数量
// 初始化粒子
for (let i = 0; i < particleNum; i++) {
particles.push(new Particle());
}
// 动画
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
particles.forEach((particle, index) => {
particle.draw(); // 绘制粒子
particle.x += particle.vx;
particle.y += particle.vy;
// 碰撞检测,边缘反弹
if (particle.x - particle.radius < 0 || particle.x + particle.radius > canvas.width) {
particle.vx = -particle.vx;
}
if (particle.y - particle.radius < 0 || particle.y + particle.radius > canvas.height) {
particle.vy = -particle.vy;
}
// 粒子之间连线
for (let i = index + 1; i < particleNum; i++) {
const distance = Math.sqrt((particles[i].x - particle.x) ** 2 + (particles[i].y - particle.y) ** 2);
if (distance < 100) {
ctx.beginPath();
ctx.moveTo(particle.x, particle.y);
ctx.lineTo(particles[i].x, particles[i].y);
ctx.strokeStyle = `rgba(255,255,255,${(100 - distance) / 100})`;
ctx.stroke();
}
}
});
// 标注文本
// ctx.font = "18px Arial";
// ctx.fillStyle = "white";
// ctx.fillText("自由扩散的粒子特效", canvas.width / 2 - 100, 50);
requestAnimationFrame(animate);
}
animate();
}
}
</script>