// http://drublic.de/demo/multiply-canvas/
// Thanks to http://albertogasparin.it/articles/2011/05/html5-multiply-filter-canvas/
var multiplyFilter = (function() {
//** private vars **//
var multiplyColor,
imageBottom,
canvas;
//** private functions **//
function draw() {
var context, imgData, pix,
w = imageBottom.width,
h = imageBottom.height;
canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
imageBottom.parentNode.insertBefore(canvas, imageBottom);
if (!canvas.getContext) { return; }
// get 2d context
context = canvas.getContext('2d');
// draw the image on the canvas
context.drawImage(imageBottom, 0, 0);
// Get the CanvasPixelArray from the given coordinates and dimensions.
imgData = context.getImageData(0, 0, w, h);
pix = imgData.data;
// Loop over each pixel and change the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i ] = multiplyPixels(multiplyColor[0], pix[i ]); // red
pix[i+1] = multiplyPixels(multiplyColor[1], pix[i+1]); // green
pix[i+2] = multiplyPixels(multiplyColor[2], pix[i+2]); // blue
// pix[i+3] is alpha channel (ignored)
}
// Draw the result on the canvas
context.putImageData(imgData, 0, 0);
}
//** helper function **//
function multiplyPixels(topValue, bottomValue) {
// the multiply formula
return topValue * bottomValue / 255;
}
//** public functions **//
return {
init : function(imageId, color) {
imageBottom = document.getElementById(imageId);
multiplyColor = color;
// lauch the draw function as soon as the image is loaded
if(imageBottom.width > 100) { // image loaded
draw();
} else { // not yet
setTimeout(function() { multiplyFilter.init(imageId,color); }, 100);
}
}
}
})();
multiplyFilter.init('base', [255, 0, 0]);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.