-
Notifications
You must be signed in to change notification settings - Fork 0
/
Common.js
66 lines (57 loc) · 1.21 KB
/
Common.js
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
function vec(x = 0, y = 0) {
return createVector(x, y)
}
function add(a, b) {
let v = vec()
v.x = a.x + b.x
v.y = a.y + b.y
return v;
}
function sub(a, b) {
let v = vec()
v.x = a.x - b.x
v.y = a.y - b.y
return v;
}
function mul(a, b) {
if (!b) b = 0
let v = vec()
v.x = a.x * b
v.y = a.y * b
return v;
}
function rectContains(x, y, w, h, pt) {
return x < pt.x && x + w > pt.x
&& y < pt.y && y + h > pt.y
}
function circleContains(x, y, radius, pt) {
var diff = sub(vec(x, y), pt)
return diff.magSq() < radius * radius
}
function outOfBounds(a) {
return !rectContains(0, 0, width, height, a)
}
function getImageData(image, scale) {
let canvas = document.createElement("canvas")
canvas.width = image.width * scale
canvas.height = image.height * scale
let ctx = canvas.getContext("2d")
ctx.scale(scale, scale)
ctx.drawImage(image, 0, 0)
return ctx.getImageData(0, 0, canvas.width, canvas.height)
}
function getColor(imageData, x, y, width, imageScale) {
let pixels = imageData.data
x = (x / imageScale) | 0
y = (y / imageScale) | 0
w = width / imageScale
let index = (y * w + x) * 4
return [
pixels[index],
pixels[index + 1],
pixels[index + 2]
]
}
function xyToIndex(x, y, w) {
return y * w + x
}