
export class Energy {
public radius = 0;
public pos = {x: 0, y: 0};
public cp = {x: 0, y: 0};
public speed = 1;
public coefficient = {x: 0, y: 0};
public dir = [
{x: 1, y: 1},
{x: 1, y: -1},
{x: -1, y: 1},
{x: -1, y: 1},
];
constructor(private ctx: CanvasRenderingContext2D, private rect: { x: number, y: number }) {
this.init();
}
private init(): void {
// 初始化半径及位置
this.radius = Math.ceil(Math.random() * 2);
// 运行速度,每帧的位移量, 最大速度为5,受半径影响
this.speed = this.radius;
this.pos = this.randomRectOuterPos();
// 求容器的中心点
this.cp.x = this.rect.x / 2;
this.cp.y = this.rect.y / 2;
// 运行速度,每帧的位移量, 最大速度为5
this.speed = this.radius;
// 求分量的偏移角度
const angle = Math.atan2(this.pos.x - this.cp.x, this.pos.y - this.cp.y);
// 分别计算出x\y方向上的偏移系数,网页坐标和数学的0点坐标是关于y轴对称
this.coefficient.x = -Math.sin(angle);
this.coefficient.y = -Math.cos(angle);
}
private randomRectOuterPos(): { x: number, y: number } {
// 先随机生成x轴还是y轴
const p = {x: 0, y: 0};
const dir = Math.random() > 0.5 ? -1 : 1;
if (Math.random() > 0.5) {
// 先x轴
p.x = dir > 0 ? (Math.ceil(Math.random() * 100) + this.rect.x) : (Math.ceil(Math.random() * -100));
p.y = Math.ceil(Math.random() * this.rect.y);
} else {
p.y = dir > 0 ? (Math.ceil(Math.random() * 100) + this.rect.y) : (Math.ceil(Math.random() * -100));
p.x = Math.ceil(Math.random() * this.rect.x);
}
return p;
}
public run() {
// 向容器的中心位置移动
this.pos.x += this.coefficient.x * this.speed;
this.pos.y += this.coefficient.y * this.speed;
// 达到中心之后,重新随机位置
if (Math.abs(this.pos.x - this.cp.x) < 2 || Math.abs(this.pos.y - this.cp.y) < 2) {
this.init();
}
this.ctx.beginPath();
this.ctx.arc(this.pos.x, this.pos.y, this.radius, 0, 2*Math.PI);
this.ctx.fillStyle = '#eef1a4';
this.ctx.fill();
this.ctx.closePath();
}
public drawCenterEnergy(img?: any): void {
// 绘制中心点
this.ctx.beginPath();
this.ctx.drawImage(img, this.cp.x - img.width / 2, this.cp.y - 10);
// this.ctx.fillStyle = '#ff0000';
// this.ctx.fill();
this.ctx.closePath();
}
}
// const energys: Energy[] = [];
// for (let i = 0; i < 100; i++) {
// energys.push(new Energy(ctx, {x: pNode.clientWidth, y: pNode.clientHeight}));
// }
// const img = new Image();
// img.src = 'assets/test1.png';
// const update = () => {
// ctx.clearRect(0, 0, pNode.clientWidth, pNode.clientHeight);
// energys[0].drawCenterEnergy(img);
// energys.forEach(energy => energy.run());
// window.requestAnimationFrame(update);
// }
// update();