HTML5 Canvas: Colorize image

xpepermint picture xpepermint · Mar 4, 2012 · Viewed 9.2k times · Source

I would like to change the color of the image/canvas. My existing code:

var loader = new PxLoader()
var image = loader.addImage('images/balloon.png')
loader.addCompletionListener(functio() {
  var canvas = $("<canvas>").attr("width", "200").attr("height", "200");
  var context = canvas[0].getContext('2d');
  context.clearRect(0, 0, 200, 200);
  context.drawImage(image, 0, 0);
  // colorize??????
});

How can I colorize it - further manipulation of the context (I would like to use Pixastic.process if possible)?

Answer

alex picture alex · Mar 4, 2012

If by colorize you mean change the background colour, then use....

context.fillColor = '#f0f';

context.fillRect(0, 0, canvas.attr('width'), canvas.attr('height'));

If you mean to tint the colour, try...

var data = ctx.getImageData(0, 0, canvas.attr('width'), canvas.attr('height'));

for (var i = 0, length = data.data.length; i < length; i += 4) {
    data.data[i] = Math.max(255, data.data[i]);
}

context.putImageData(data, 0, 0);

jsFiddle.

That will max the red value for each pixel. Experiment with it to get the effect you desire.