Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

But the imageData.data array contains values in rgba. Actually each 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 manipulate imageData? An api that would abstract the raw data so that - data[0] = rgba, data[1] = rgba etc?

And that might have methods like - data[0].setValueHSL(60, 100%, 50%);

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

like image 802
Duncan Gravill Avatar asked Oct 07 '22 21:10

Duncan Gravill


1 Answers

I am not sure if you are still looking for the answer since this was asked a long time ago. But I was trying to do the same and encountered the answer on Why doesn't this Javascript RGB to HSL code 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) + '%)';

}
like image 93
eltongonc Avatar answered Oct 10 '22 02:10

eltongonc