Skip to content

Instantly share code, notes, and snippets.

@nhusher
Last active May 13, 2016 19:45
Show Gist options
  • Save nhusher/54450571109ce28b67888ba2e3dc2e7f to your computer and use it in GitHub Desktop.
Save nhusher/54450571109ce28b67888ba2e3dc2e7f to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<title>Remap Colors</title>
</head>
<body>
<img src="./customer-star.png" style="background-color: #444" />
<script src="./map.js" charset="utf-8"></script>
</body>
</html>
// A static promise for the customer star
// All the color mapping stuff is going to depend on it
const clusterImage = new Promise((resolve) => {
let i = new Image();
i.onload = () => {
resolve(i);
};
i.src = './customer-star.png';
});
const MAPPED_IMAGE_CACHE = {};
// hex string => [ red, green, blue, alpha ]
// where alpha is always null, it's just a placeholder for color mapping below
function getRgbaFromHex(hex) {
return [
parseInt(hex.slice(0,2), 16),
parseInt(hex.slice(2,4), 16),
parseInt(hex.slice(4,6), 16),
null // can't get rgba from hex
];
}
// Maps an image from grayscale to a particular color
// color => Promise<img>
function getColorMappedImage(color) {
if(MAPPED_IMAGE_CACHE[color]) {
return MAPPED_IMAGE_CACHE[color];
}
let promise = clusterImage.then(img => {
let c = document.createElement('canvas'),
rgba = getRgbaFromHex(color);
c.height = img.height;
c.width = img.width;
let ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0);
let allData = ctx.getImageData(0, 0, c.width, c.height),
pixelData = allData.data;
for(let i = 0, l = pixelData.length; i < l; i += 1) {
let component = rgba[i % 4]; // get the color we want to replace
if(component) {
pixelData[i] = component * (pixelData[i]/255);
}
}
ctx.clearRect(0, 0, allData.width, allData.height);
ctx.putImageData(allData, 0,0);
let image = new Image();
image.src = c.toDataURL();
return image;
});
MAPPED_IMAGE_CACHE[color] = promise; // Only do the work once
return promise;
}
['e85ea5','ff795d','c569ff','49ada6'].forEach(function(color) {
getColorMappedImage(color).then(function(image) {
document.body.appendChild(image);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment