Skip to content

Instantly share code, notes, and snippets.

@flurin
Created October 17, 2011 19:24
Show Gist options
  • Save flurin/1293513 to your computer and use it in GitHub Desktop.
Save flurin/1293513 to your computer and use it in GitHub Desktop.
Test canvas color blending
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.1/mootools-yui-compressed.js"></script>
</head>
<body>
<img src="200.jpeg" id="img">
<script>
function convertToCanvas(img){
var c = document.createElement("canvas");
var s = img.getSize();
var ctx = c.getContext("2d");
c.width = s.x;
c.height = s.y;
ctx.drawImage(img,0,0);
img.grab(c,"after");
img.dispose();
return c;
}
var Filters = {};
Filters.getPixels = function(cnv) {
var ctx = cnv.getContext("2d");
return ctx.getImageData(0,0,cnv.width,cnv.height);
};
Filters.threshold = function(pixels, threshold) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
var v = (0.2126*r + 0.7152*g + 0.0722*b >= threshold) ? 255 : 0;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
Filters.grayscale = function(pixels, args) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
// CIE luminance for the RGB
// The human eye is bad at seeing red and blue, so we de-emphasize them.
var v = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
Filters.grayscale2 = function(pixels, args) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
// CIE luminance for the RGB
// The human eye is bad at seeing red and blue, so we de-emphasize them.
// var v = 0.2126*r + 0.7152*g + 0.0722*b;
var v = (r + g + b * 2) / 3
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
Filters.filterImage = function(filter, cnv, var_args) {
var args = [this.getPixels(cnv)];
for (var i=2; i<arguments.length; i++) {
args.push(arguments[i]);
}
return filter.apply(null, args);
};
function testFilter(cnv){
var ctx = cnv.getContext("2d");
var data = Filters.filterImage(Filters.grayscale2, cnv);
ctx.putImageData(data,0,0);
}
$('img').addEvent("load", function(){
cnv = convertToCanvas($('img'));
testFilter(cnv)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment