Changing the pixel in the imageData canvas for hsl (60, 100%, 50%)

I would like to change the pixels of an HTML5 canvas value to hsl . It can be any hsl value chosen by the user.

I can get canvas imageData using var imageData = canvas.getImageData(0, 0, 200, 200);

But the imageData.data array contains the values ​​in rgba . In fact, every value in the array is a byte, so -

data[0] = r, data[1] = b, data[2] = g, data[3] = a, data[4] = r, data[5] = b, data[6] = g, data[7] = a etc.

Is there an api that can be used to control imageData? api , which would abstract the raw data so that - data[0] = rgba, data[1] = rgba , etc.?

And this can have methods such as - data[0].setValueHSL(60, 100%, 50%);

If this api does not exist, is there a class that can create / represent the hsl value and which can convert the value to rgb?

+4
source share
2 answers

You can write one as simple as this

 parseImageData = function(imageData) { var newImageData = []; for ( var i = imageData - 1; i>0; i-4) { newImageData.push([ imageData[i], imageData[i-1], imageData[i-2], imageData[i-3] ]); } return newImageData; } 

then if you want to return it

 parseNewImageData = function ( newImageData ) { var imageData = []; for ( var i = newImageData - 1; i>=0; --i) { imageData.push( imageData[i][0] ); imageData.push( imageData[i][1] ); imageData.push( imageData[i][2] ); imageData.push( imageData[i][3] ); } return imageData; } 

Super easy and you can do it specifically for what you need!

Hope this helps!

+1
source

I'm not sure if you are still looking for an answer, as it was asked a long time ago. But I tried to do the same and ran into the answer to Why does this Javascript RGB for HSL code not work? this should do the trick:

 function rgbToHsl(r, g, b) { r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return 'hsl(' + Math.floor(h * 360) + ',' + Math.floor(s * 100) + '%,' + Math.floor(l * 100) + '%)'; } 
+1
source

All Articles