Skip to content

Instantly share code, notes, and snippets.

@vegeta897
Created February 9, 2018 20:48
Show Gist options
  • Save vegeta897/45a3cdb866500154ac17e9cc2a89f27f to your computer and use it in GitHub Desktop.
Save vegeta897/45a3cdb866500154ac17e9cc2a89f27f to your computer and use it in GitHub Desktop.
colorize: function(options) {
var canvas = document.createElement('canvas');
canvas.width = options.image.width;
canvas.height = options.image.height;
var context = canvas.getContext('2d');
context.drawImage(options.image, 0, 0, options.image.width, options.image.height,
0, 0, options.image.width, options.image.height);
context.globalCompositeOperation = 'color';
var colorCanvas = document.createElement('canvas');
colorCanvas.width = options.image.width;
colorCanvas.height = options.image.height;
var colorContext = colorCanvas.getContext('2d');
colorContext.fillStyle = options.color;
colorContext.globalAlpha = options.alpha;
colorContext.fillRect(0, 0, options.image.width, options.image.height);
if(options.regions) { // Paint custom regions if specified
for(var i = 0; i < options.regions.length; i++) {
var reg = options.regions[i];
colorContext.clearRect(reg.x, reg.y, reg.w, reg.h);
colorContext.fillStyle = reg.color ? reg.color : options.color;
colorContext.globalAlpha = reg.alpha ? reg.alpha : options.alpha;
colorContext.fillRect(reg.x, reg.y, reg.w, reg.h);
}
}
context.drawImage(colorCanvas,0,0);
applyAlpha(options.image, canvas); // Restore original alpha channel
return canvas;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment