Skip to content

Commit 9606544

Browse files
Colors!
1 parent 97256b6 commit 9606544

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

assets/color.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
function color(imgSrc){
2+
var img = document.createElement('img');
3+
img.src = imgSrc;
4+
var rgb = getAverageRGB(img);
5+
return rgb
6+
}
7+
8+
function getAverageRGB(imgEl) {
9+
var blockSize = 5, // only visit every 5 pixels
10+
defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
11+
canvas = document.createElement('canvas'),
12+
context = canvas.getContext && canvas.getContext('2d'),
13+
data, width, height,
14+
i = -4,
15+
length,
16+
rgb = {r:0,g:0,b:0},
17+
count = 0;
18+
19+
if (!context) {
20+
return defaultRGB;
21+
}
22+
23+
height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
24+
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
25+
26+
context.drawImage(imgEl, 0, 0);
27+
28+
try {
29+
data = context.getImageData(0, 0, width, height);
30+
} catch(e) {
31+
/* security error, img on diff domain */alert('x');
32+
return defaultRGB;
33+
}
34+
35+
length = data.data.length;
36+
37+
while ( (i += blockSize * 4) < length ) {
38+
++count;
39+
rgb.r += data.data[i];
40+
rgb.g += data.data[i+1];
41+
rgb.b += data.data[i+2];
42+
}
43+
44+
// ~~ used to floor values
45+
rgb.r = ~~(rgb.r/count);
46+
rgb.g = ~~(rgb.g/count);
47+
rgb.b = ~~(rgb.b/count);
48+
49+
return rgb;
50+
51+
}

html/game.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
<!-- Latest compiled and minified CSS -->
2121
<link rel="stylesheet" href="https://bootswatch.com/cyborg/bootstrap.min.css" crossorigin="anonymous">
2222
<!-- Latest compiled and minified JavaScript -->
23+
<script src="color.js"></script>
2324
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
2425
<body style="background-color: transparent;">
2526
<center>

0 commit comments

Comments
 (0)