2

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)?

xpepermint
  • 35,055
  • 30
  • 109
  • 163
  • 2
    Did you look at this? http://stackoverflow.com/questions/2688961/how-do-i-tint-an-image-with-html5-canvas – n a Mar 04 '12 at 12:18

2 Answers2

5

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.

alex
  • 479,566
  • 201
  • 878
  • 984
  • No... I would like to "tint" the image so it would have more red color for example. – xpepermint Mar 04 '12 at 12:15
  • @xpepermint Get the image data (`getImageData()`) and increase the *red* value for each pixel. – alex Mar 04 '12 at 12:18
  • @xpepermint I am doing an example and will update the post when it's ready. – alex Mar 04 '12 at 12:30
  • 2
    @alex BTW, I didn't get this `Math.max(255, data.data[i])`. I guess it will always return 255 so why to use this function? Why not `data.data[i] = 255` simply? – Mohammad Usman Jan 03 '18 at 10:37
-1

explained in this question:

How do i tint an image with HTML5 Canvas?

and in here: http://www.playmycode.com/blog/2011/06/realtime-image-tinting-on-html5-canvas/

Community
  • 1
  • 1
Itai Bar-Haim
  • 1,686
  • 16
  • 40