-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvas.ts
82 lines (65 loc) · 2.17 KB
/
canvas.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
import { ConfigOptions } from './interfaces';
import { ParticleOptions, Particle } from './particle';
import { DecentralizedParticles } from './core';
import { Segment, SegmentOptions } from './segment';
export function createParticlesOnCanvas(
element: HTMLCanvasElement,
configOptions?: ConfigOptions,
particleOptions?: ParticleOptions,
segmentOptions?: SegmentOptions
) {
const ctx = element.getContext(`2d`);
let width = () => element.clientWidth;
let height = () => element.clientHeight;
if (window && 'onresize' in window) {
window.onresize = setDimensions;
}
function setDimensions() {
element.width = width();
element.height = height();
}
setDimensions();
const particles = new DecentralizedParticles(configOptions, particleOptions, segmentOptions);
particles.beforeUpdate(() => {
ctx.clearRect(0, 0, width(), height());
});
particles.createParticle(particle => {
let img: HTMLOrSVGImageElement;
if (isImage(particle.background)) {
img = document.createElement('img');
img.src = particle.background;
}
drawParticle(particle, img);
particle.onUpdate(() => drawParticle(particle, img));
});
particles.createSegment(segment => {
drawSegment(segment);
segment.onUpdate(() => drawSegment(segment));
});
function drawParticle(particle: Particle, img?: HTMLOrSVGImageElement) {
if (img) {
ctx.drawImage(img, particle.positionX * width(), particle.positionY * height(), particle.size, particle.size);
} else {
ctx.beginPath();
ctx.arc(particle.positionX * width(), particle.positionY * height(), particle.size / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = particle.background;
ctx.fill();
}
}
function drawSegment(segment: Segment) {
ctx.beginPath();
ctx.moveTo(segment.positionX1 * width(), segment.positionY1 * height());
ctx.lineTo(segment.positionX2 * width(), segment.positionY2 * height());
ctx.strokeStyle = segment.stroke;
ctx.lineWidth = segment.width;
ctx.stroke();
}
function isImage(background: string) {
const char1 = background.charAt(0);
if (char1 === `.` || char1 === `/`) return true;
if (/^data:image\//.test(background)) return true;
return false;
}
particles.start();
return particles;
}