Skip to content

Instantly share code, notes, and snippets.

@Goos
Created June 4, 2013 08:34
Show Gist options
  • Save Goos/5704502 to your computer and use it in GitHub Desktop.
Save Goos/5704502 to your computer and use it in GitHub Desktop.
JShoop.js - gradient mapping images with canvas
(function (JShoop, $, window) {
function test_origin(url) {
var loc = window.location,
a = document.createElement('a');
a.href = url;
var cors = (a.hostname == loc.hostname &&
a.port == loc.port &&
a.protocol == loc.protocol);
return cors;
}
function gradient_map(img, red, green, blue) {
if (!test_origin(img.src)) {
return null;
}
if (!JShoop.scratchbox) {
var success = init();
if (!success) {
return null;
}
}
var can = JShoop.scratchbox,
width = img.width,
height = img.height;
can.width = width;
can.height = height;
var ctx = can.getContext("2d");
img.crossOrigin = "Anonymous";
ctx.drawImage(img, 0, 0);
var img_data = ctx.getImageData(0, 0, width, height);
w2 = width / 2;
var inpos, outpos,
r, g, b, a,
tr, tg, tb,
lightness;
tr = red/255;
tg = green/255;
tb = blue/255;
for (y = 0; y < height; y++) {
inpos = outpos = y * width * 4;
for (x = 0; x < width; x++) {
r = img_data.data[inpos++];
g = img_data.data[inpos++];
b = img_data.data[inpos++];
a = img_data.data[inpos++];
lightness = (r + g + b) * (1 / 3);
img_data.data[outpos++] = tr * lightness;
img_data.data[outpos++] = tg * lightness;
img_data.data[outpos++] = tb * lightness;
img_data.data[outpos++] = a;
}
}
ctx.putImageData(img_data, 0, 0);
var ret_img = new Image();
ret_img.src = can.toDataURL();
ctx.clearRect(0, 0, width, height);
return ret_img;
}
function init () {
JShoop.scratchbox = document.createElement('canvas');
if (!(JShoop.scratchbox.getContext && JShoop.scratchbox.getContext('2d'))) {
return false;
}
JShoop.scratchbox.setAttribute('height', '0');
JShoop.scratchbox.setAttribute('width', '0');
JShoop.scratchbox.style.display = "none";
document.body.appendChild(JShoop.scratchbox);
return true;
}
JShoop.gradient_map = gradient_map;
})(window.JShoop = window.JShoop || {}, $, window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment