-
Notifications
You must be signed in to change notification settings - Fork 0
/
painter.ts
92 lines (81 loc) · 2.25 KB
/
painter.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
import { canvas, context } from './constants';
import { Position } from './Particle';
export const wipe = () => context.clearRect(0, 0, canvas.width, canvas.height);
export const wipeToFade = () => {
context.fillStyle = 'rgba(0, 0, 0, 0.1)';
context.fillRect(0, 0, canvas.width, canvas.height);
};
export const circle = (point, { size = 10, color = 'white' }) => {
context.beginPath();
context.arc(point.x, point.y, size, 0, Math.PI * 2);
context.fillStyle = color;
context.fill();
context.closePath();
};
export const line = (
from: Position,
to: Position,
{ color = 'white', size = 12 }
) => {
context.beginPath();
context.moveTo(from.x, from.y);
context.lineTo(to.x, to.y);
context.stroke();
context.strokeStyle = color;
context.lineWidth = size;
context.closePath();
};
export const textCoordinates = (text = 'A') => {
let coordinates = [];
const positionAdjustement = 20;
const positionMultiplier = 10;
const drawingArea = {
width: 100,
height: 100,
};
// Opacity is represented inside a clamped array, 255 is 1, so 128 marks ~50%
const minPixelOpacity = 128;
// Stylinng
context.fillStyle = 'white';
context.font = '24px Verdana';
context.fillText(text, 0, 30);
// The Uint8ClampedArray
const imageData = context.getImageData(
0,
0,
drawingArea.width,
drawingArea.height
);
// Iterate over data grid, 100x100
// Each pixel represented in rgba ( 4 items inside the array )
const opacityRepresentationIndex = 3;
for (
let y = 0;
y < drawingArea.height;
y++
) {
for (
let x = 0;
x < drawingArea.width;
x++
) {
const yOpacityIndex = y * 4;
const xOpacityIndex = x * 4;
// The current pixel opacity index representationn
const opacityIndex =
drawingArea.height * yOpacityIndex +
xOpacityIndex +
opacityRepresentationIndex;
// The current pixel opacity value
const pixelOpacity = imageData.data[opacityIndex];
// If not transparent, adds coordinate
if (pixelOpacity > minPixelOpacity) {
coordinates.push({
x: x * positionMultiplier + positionAdjustement,
y: y * positionMultiplier + positionAdjustement,
});
}
}
}
return coordinates;
};