Bagel03
Bagel03

Reputation: 715

How Change Hue of Javascript/Html Canvas Image

I have a spritesheet image made up of 16*16 tiles. I already have a good loading system and I have handled drawing them without losing the aspect ratio. The problem is that I want to get a 16 * 16 tile of that sheet, copy it, and change the hue of the new image by some amount.

I think I have copying working, but here is all my code

let temp = document.createElement('canvas').getContext('2d');

temp.drawImage('spritesheet.png',0,0)

let pixels = temp.getImageData(0, 0, 16,16);

//manipulate them so that the hue is changed (can't find code for)

let Shifted = new Image();
Shifted.src = temp.canvas.toDataUrl("image/png");

Upvotes: 0

Views: 858

Answers (1)

flowb
flowb

Reputation: 30

This QA can be useful (explaining how to change the image colors). Otherwise a canvas filter can be applied to the image, this article demonstrate it in details.

Example from the linked howto:

var gradientColors = createGradient('#0096ff', '#ff00f0');
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
applyGradient(imageData.data);

for (var i = 0; i < data.length; i += 4) {
  // Get the each channel color value
  var redValue = data[i];
  var greenValue = data[i+1];
  var blueValue = data[i+2];

  // Mapping the color values to the gradient index
  // Replacing the grayscale color value with a color for the duotone gradient
  data[i] = gradientColors[redValue].r;
  data[i+1] = gradientColors[greenValue].g;
  data[i+2] = gradientColors[blueValue].b;
  data[i+3] = 255;
}

Upvotes: 1

Related Questions