本文介绍了将canvas imageData中的像素更改为hsl(60,100%,50%)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 HTML5画布的像素更改为 hsl 值。它可以是用户选择的任何 hsl 值。

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.

我可以使用<$获取canvas imageData c $ c> var imageData = canvas.getImageData(0,0,200,200);

但是 imageData.data 数组包含 rgba 中的值。实际上,数组中的每个值都是一个字节,所以 -

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 等。

是否有 api 可以用来操纵imageData?一个 api ,它将抽象原始数据,以便 - data [0] = rgba,data [1] = rgba 等等?

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?

这可能有类似的方法 - data [0] .setValueHSL(60,100%,50%);

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

如果这个api不存在,那么有一个类可以创建/表示一个hsl值,并且可以将该值转换为rgb吗?

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?

推荐答案

我不确定你是否仍在寻找答案,因为这是很久以前的问题。但我试图做同样的事情并在,这应该可以解决问题:

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) + '%)';

}

这篇关于将canvas imageData中的像素更改为hsl(60,100%,50%)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:41