forked from codepo8/pixels-and-colours
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06-compare.html
127 lines (116 loc) · 2.56 KB
/
06-compare.html
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="UTF-8">
<title>Compare pixels</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
font-family: helvetica,arial,sans-serif;
}
canvas {
display: block;
background: #ccc;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
var c = document.querySelector('canvas');
var cx = c.getContext('2d');
var mousedown = false;
var oldx = null;
var oldy = null;
var pixels = null;
var letterpixels = null;
function setupCanvas() {
c.height = 480;
c.width = 320;
cx.lineWidth = 20;
cx.lineCap = 'round';
cx.strokeStyle = 'rgb(0, 0, 50)';
cx.font = 'bold 300px helvetica';
cx.fillStyle = 'rgb(255, 0, 0)';
cx.textBaseline = 'middle';
drawletter('y');
pixels = cx.getImageData(0, 0, c.width, c.height);
letterpixels = getpixelamount(255, 0, 0);
}
function drawletter(letter) {
var centerx = (c.width - cx.measureText(letter).width) / 2;
var centery = c.height / 2;
cx.fillText(letter, centerx, centery);
};
function showerror(error) {
mousedown = false;
alert(error);
};
function paint(x, y) {
var colour = getpixelcolour(x, y);
if (colour.a === 0) {
showerror('you are outside');
} else {
cx.beginPath();
if (oldx > 0 && oldy > 0) {
cx.moveTo(oldx, oldy);
}
cx.lineTo(x, y);
cx.stroke();
cx.closePath();
oldx = x;
oldy = y;
}
};
function getpixelcolour(x, y) {
var index = ((y * (pixels.width * 4)) + (x * 4));
return {
r: pixels.data[index],
g: pixels.data[index + 1],
b: pixels.data[index + 2],
a: pixels.data[index + 3]
};
}
function getpixelamount(r, g, b) {
var pixels = cx.getImageData(0, 0, c.width, c.height);
var all = pixels.data.length;
var amount = 0;
for (i = 0; i < all; i += 4) {
if (pixels.data[i] === r &&
pixels.data[i + 1] === g &&
pixels.data[i + 2] === b) {
amount++;
}
}
return amount;
};
function pixelthreshold() {
if (getpixelamount(0, 0, 50) / letterpixels > 0.35) {
alert('you got it!');
}
};
function onmousedown(ev) {
mousedown = true;
ev.preventDefault();
};
function onmouseup(ev) {
mousedown = false;
pixelthreshold();
ev.preventDefault();
};
function onmousemove(ev) {
var x = ev.clientX;
var y = ev.clientY;
if (mousedown) {
paint(x, y);
}
};
c.addEventListener('mousedown', onmousedown, false);
c.addEventListener('mouseup', onmouseup, false);
c.addEventListener('mousemove', onmousemove, false);
setupCanvas();
</script>
</body>
</html>