-
Notifications
You must be signed in to change notification settings - Fork 0
/
sierpinksi.component.ts
110 lines (86 loc) · 2.64 KB
/
sierpinksi.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { Component, ElementRef, ViewChild, OnInit, OnDestroy, Input } from '@angular/core';
interface IPoint {
x: number;
y: number;
}
const FULL_ARC = Math.PI * 2;
@Component({
selector: 'nologig-triangle-sierpinski',
templateUrl: './triangle.component.html',
styleUrls: ['./triangle.component.scss']
})
export class TriangleComponent implements OnDestroy, OnInit {
@ViewChild('geometry') public canvasGeo: ElementRef;
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
cWidth = window.innerWidth;
cHeight = window.innerHeight;
points: IPoint[] = [];
next_Point = {
x: Math.random() * this.cWidth,
y: Math.random() * this.cHeight
};
constructor() { }
ngOnInit(): void {
// Get canvas & context
this.canvas = this.canvasGeo.nativeElement;
this.ctx = this.canvas.getContext('2d');
// Canvas settings
this.canvas.width = this.cWidth;
this.canvas.height = this.cHeight;
this.ctx.strokeStyle = '#0ff';
this.ctx.fillStyle = '#0ff';
this.ctx.fillText('A', 4, this.cHeight);
this.ctx.fillText('B', this.cWidth - 32, this.cHeight);
this.ctx.fillText('C', this.cWidth * .5, 32);
// ToDo: implement method to attach/capture events => test
this.attachEvent(this.canvas, 'click', this.createNode);
this.points.push({
x: 32,
y: this.cHeight - 32
});
this.points.push({
x: this.cWidth - 32,
y: this.cHeight - 32
});
this.points.push({
x: this.cWidth * .5,
y: 32
});
this.pointXY(this.points[0].x, this.points[0].y);
this.pointXY(this.points[1].x, this.points[1].y);
this.pointXY(this.points[2].x, this.points[2].y);
this.render();
}
attachEvent(ele: HTMLElement, event: string, fn: (e: KeyboardEvent | MouseEvent) => void) {
ele.addEventListener(event, fn);
}
detachEvent(ele: HTMLElement, event: string, fn: (e: KeyboardEvent | MouseEvent) => void) {
ele.removeEventListener(event, fn);
}
createNode = (e: MouseEvent) => {
this.points.push({
x: e.clientX,
y: e.clientY
});
}
ngOnDestroy(): void {
this.detachEvent(this.canvas, 'click', this.createNode);
}
render(): void {
requestAnimationFrame(() => this.render());
this.pointXY(this.next_Point.x, this.next_Point.y);
this.update();
}
update(): void {
let i = Math.floor(Math.random() * this.points.length);
this.next_Point.x = (this.points[i].x + this.next_Point.x) * .5;
this.next_Point.y = (this.points[i].y + this.next_Point.y) * .5;
return;
}
pointXY(x: number, y: number): void {
this.ctx.beginPath();
this.ctx.arc(x, y, 2, 0, FULL_ARC);
this.ctx.fill();
}
}