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

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?

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

You could write one its 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 convert it back
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 make it do specifically what you need it to!
I hope this helps!

Related

Converting between color models

I'm trying to make buttons for converting between color models (hex, rgb, hsl).
I've created a button that generates a random color when clicked on.
And I've created a class that generates the random color in rgb and has methods to convert it to hex or hsl.
I tried creating a "click" event listener on each of the color model buttons but I'm not able to access the newly generated color object that I made through the class (block scope).
Should I have just used normal functions to convert instead of a class constructor?
const colorName = document.querySelector(".colorName");
const genColorBtn = document.querySelector("#genColorBtn");
const hexBtn = document.querySelector("#hexBtn");
const rgbBtn = document.querySelector("#rgbBtn");
const hslBtn = document.querySelector("#hslBtn");
// Generate Random Color
const genRandomColor = () => {
const r = Math.floor(Math.random() * 255 + 1);
const g = Math.floor(Math.random() * 255 + 1);
const b = Math.floor(Math.random() * 255 + 1);
return new Color(r, g, b);
};
genColorBtn.addEventListener("click", function () {
const newColor = genRandomColor();
document.body.style.backgroundColor = newColor.rgb();
colorName.innerText = newColor.rgb();
});
// Color Model Conversions
class Color {
constructor(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
this.calcHSL();
}
// Add methods to the prototype.
hex() {
const { r, g, b } = this;
return (
"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
);
}
rgb() {
const { r, g, b } = this;
return `rgb(${r}, ${g}, ${b})`;
}
hsl() {
const { h, s, l } = this;
return `hsl(${h}, ${s}%, ${l}%)`;
}
// For hsl
calcHSL() {
let { r, g, b } = this;
// Make r, g, and b fractions of 1
r /= 255;
g /= 255;
b /= 255;
// Find greatest and smallest channel values
let cmin = Math.min(r, g, b),
cmax = Math.max(r, g, b),
delta = cmax - cmin,
h = 0,
s = 0,
l = 0;
if (delta == 0) h = 0;
else if (cmax == r)
// Red is max
h = ((g - b) / delta) % 6;
else if (cmax == g)
// Green is max
h = (b - r) / delta + 2;
// Blue is max
else h = (r - g) / delta + 4;
h = Math.round(h * 60);
// Make negative hues positive behind 360°
if (h < 0) h += 360;
// Calculate lightness
l = (cmax + cmin) / 2;
// Calculate saturation
s = delta == 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
// Multiply l and s by 100
s = +(s * 100).toFixed(1);
l = +(l * 100).toFixed(1);
// Assign h, s, l to the object instance so that we can reuse it.
this.h = h;
this.s = s;
this.l = l;
}
}
<body>
<main>
<h1>Random Color Flipper</h1>
<h2>Color: <span class="colorName">rgb(255, 255, 255)</span></h2>
<div class="colorModes">
<button id="hexBtn">hex</button>
<button id="rgbBtn">rgb</button>
<button id="hslBtn">hsl</button>
</div>
<button id="genColorBtn">Generate Color</button>
</main>
<script src="app.js"></script>
</body>
Your code seems fine, but your hex, rgb and hsl buttons were not wired up. I added a variable curRGB to store the current RGB values (though there is probably a more elegant getter/setter for your Class that could be written). I did take a stab at the hexBtn listener:
hexBtn.addEventListener("click", function () {
colorName.innerText = new Color(...curRGB).hex();
});
const colorName = document.querySelector(".colorName");
const genColorBtn = document.querySelector("#genColorBtn");
const hexBtn = document.querySelector("#hexBtn");
const rgbBtn = document.querySelector("#rgbBtn");
const hslBtn = document.querySelector("#hslBtn");
let curRGB
// Generate Random Color
const genRandomColor = () => {
const r = Math.floor(Math.random() * 255 + 1);
const g = Math.floor(Math.random() * 255 + 1);
const b = Math.floor(Math.random() * 255 + 1);
curRGB = [r, g, b]
return new Color(r, g, b);
};
genColorBtn.addEventListener("click", function () {
const newColor = genRandomColor();
document.body.style.backgroundColor = newColor.rgb();
colorName.innerText = newColor.rgb();
});
hexBtn.addEventListener("click", function () {
colorName.innerText = new Color(...curRGB).hex();
});
// Color Model Conversions
class Color {
constructor(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
this.calcHSL();
}
// Add methods to the prototype.
hex() {
const { r, g, b } = this;
return (
"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
);
}
rgb() {
const { r, g, b } = this;
return `rgb(${r}, ${g}, ${b})`;
}
hsl() {
const { h, s, l } = this;
return `hsl(${h}, ${s}%, ${l}%)`;
}
// For hsl
calcHSL() {
let { r, g, b } = this;
// Make r, g, and b fractions of 1
r /= 255;
g /= 255;
b /= 255;
// Find greatest and smallest channel values
let cmin = Math.min(r, g, b),
cmax = Math.max(r, g, b),
delta = cmax - cmin,
h = 0,
s = 0,
l = 0;
if (delta == 0) h = 0;
else if (cmax == r)
// Red is max
h = ((g - b) / delta) % 6;
else if (cmax == g)
// Green is max
h = (b - r) / delta + 2;
// Blue is max
else h = (r - g) / delta + 4;
h = Math.round(h * 60);
// Make negative hues positive behind 360°
if (h < 0) h += 360;
// Calculate lightness
l = (cmax + cmin) / 2;
// Calculate saturation
s = delta == 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
// Multiply l and s by 100
s = +(s * 100).toFixed(1);
l = +(l * 100).toFixed(1);
// Assign h, s, l to the object instance so that we can reuse it.
this.h = h;
this.s = s;
this.l = l;
}
}
<main>
<h1>Random Color Flipper</h1>
<h2>Color: <span class="colorName">rgb(255, 255, 255)</span></h2>
<div class="colorModes">
<button id="hexBtn">hex</button>
<button id="rgbBtn">rgb</button>
<button id="hslBtn">hsl</button>
</div>
<button id="genColorBtn">Generate Color</button>
</main>

Extract 'dominant' colors from HSV model? (not from RGB model)

i'm looking for a get color pallet from image.
i could get RGB data from image
getRgbData() {
this.canvas = window.document.createElement('canvas')
this.context = this.canvas.getContext('2d')
this.width = this.canvas.width = image.width || image.naturalWidth
this.height = this.canvas.height = image.height || image.naturalHeight
this.context.drawImage(image, 0, 0, this.width, this.height)
return this.context.getImageData(0, 0, this.width, this.height)
}
and convert RGB values to HSV model (rgbToHsv method wrote from https://gist.github.com/mjackson/5311256#file-color-conversion-algorithms-js-L1)
getHsvData() {
const { data, width, height } = this.getRgbData()
const pixcel = width * height
const q = 1
const array = []
for (var i = 0, r, g, b, offset; i < pixcel; i = i + q) {
offset = i * 4
r = data[offset + 0]
g = data[offset + 1]
b = data[offset + 2]
array.push({ r, g, b })
}
return array.map(l => this.rgbToHsv(l.r, l.g, l.b))
}
it result like this (it is converted data from RGB 24bit)
[
{h: 0.6862745098039215, s: 0.7727272727272727, v: 0.17254901960784313},
{h: 0.676470588235294, s: 0.723404255319149, v: 0.1843137254901961},
.....
]
color-thief and vibrant.js is get dominant color from RGB model, but i want to
get dominant color from converted HSV model.
(i heard that extract color from hsv is more fit in human eyes. is it right?)
how can i extract color form HSV model..?
First thing we need to do is get the average color of the image. We can do that by adding each color channel individually then dividing by the height and the width of the canvas.
function channelAverages(data, width, height) {
let r = 0, g = 0, b = 0
let totalPixels = width * height
for (let i = 0, l = data.data.length; i < l; i += 4) {
r += data.data[i]
g += data.data[i + 1]
b += data.data[i + 2]
}
return {
r: Math.floor(r / totalPixels),
g: Math.floor(g / totalPixels),
b: Math.floor(b / totalPixels)
}
}
Next we will want to convert the returned color's average to HSL, we can do that with this function (Which you also link to above).
function rgbToHsl(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), 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 [h, s, l];
}
So, to get our output we can do this:
let data = ctx.getImageData(0, 0, canvas.width, canvas.height)
let avg = channelAverages(data, width, height)
console.log(rgbToHsl(avg.r, avg.g, avg.b))
If we want numbers we can use in an editor (Such as PhotoShop or Gimp) to verify our results, we just need to multiply each:
h = h * 360
Example: 0.08 * 360 = 28.8
s = s * 100
Example: 0.85 * 100 = 85
l = l * 100
Example: 0.32 * 100 = 32
There is a library called Kleur.js you can use to get images but remember that it gives random color palette every time. But the dominant color will remain the same in every color pallete
// Create the Kleur Object
Kleur = new Kleur();
// Set the image link to get the palette from
imageObj = Kleur.init(imgLink);
// Wait for the image to load
imageObj.onload = function(e) {
// get the color array from the image
let colorArr = Kleur.getPixelArray(imageObj);
// pass the array to generate the color array
let array_of_pixels = Kleur.generateColorArray(colorArr);
// you can get the dominant color from the image
const dominant = Kleur.getDominant(array_of_pixels);
// log the light colors and the dominant color
console.log(light, dominant)
}
if you want to see an example for using this code visit the codepen
And if you want all the dominant colors which I think is the colors with the most pixels you can access the array_of_pixels, so you could do
// for first five dominant color
for(let x = 0; x < 5; x++){
console.log(array_of_pixels[x].hsv);
}
// for the dominant colors hsv value
console.log(dominant.hsv)
this will log the hsv values for the five most dominant color in the image(usually the dominant colors are really similar so look out for that)
Kleur js returns colors in various color space
RGB
HEX
HSV
XYZ
LAB
LCH
it also returns count which is the number of pixels that have the color

Convert a 0-1 value to a hex colour?

I'm creating an app that visualises stars using a NASA API. The colour of a star comes back as a 0 to 1 value, with 0 being pure blue, and 1 being pure red. Essentially I need to set up a way to convert 0-1 values in javascript to a sliding HEX (or rgb) scale, progressing like this:
0: blue (9aafff)
.165: blue white (cad8ff)
.33: white (f7f7ff)
.495: yellow white (fcffd4)
.66: yellow (fff3a1)
.825: orange (ffa350)
1: red (fb6252)
Is this possible? I don't have any idea how to even begin to approach this. Cheers!
The best would be to work in another color space than the RGB one. For example HSL.
Example:
var stones = [ // Your Data
{v:0, hex:'#9aafff'},
{v:.165, hex:'#cad8ff'},
{v:.33, hex:'#f7f7ff'},
{v:.495, hex:'#fcffd4'},
{v:.66, hex:'#fff3a1'},
{v:.825, hex:'#ffa350'},
{v:1, hex:'#fb6252'},
]
stones.forEach(function(s){
s.rgb = hexToRgb(s.hex);
s.hsl = rgbToHsl.apply(0, s.rgb);
});
function valueToRgbColor(val){
for (var i=1; i<stones.length; i++) {
if (val<=stones[i].v) {
var k = (val-stones[i-1].v)/(stones[i].v-stones[i-1].v),
hsl = interpolArrays(stones[i-1].hsl, stones[i].hsl, k);
return 'rgb('+hslToRgb.apply(0,hsl).map(function(v){ return v|0})+')';
}
}
throw "bad value";
}
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* #param Number r The red color value
* #param Number g The green color value
* #param Number b The blue color value
* #return Array The HSL representation
*/
function rgbToHsl(r, g, b){
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), 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 [h, s, l];
}
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* #param Number h The hue
* #param Number s The saturation
* #param Number l The lightness
* #return Array The RGB representation
*/
function hslToRgb(h, s, l){
var r, g, b;
if(s == 0){
r = g = b = l; // achromatic
}else{
function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [r * 255, g * 255, b * 255];
}
function hexToRgb(hex) {
return /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
.slice(1).map(function(v){ return parseInt(v,16) });
}
function interpolArrays(a,b,k){
var c = a.slice();
for (var i=0;i<a.length;i++) c[i]+=(b[i]-a[i])*k;
return c;
}
var stones = [ // Your Data
{v:0, hex:'#9aafff'},
{v:.165, hex:'#cad8ff'},
{v:.33, hex:'#f7f7ff'},
{v:.495, hex:'#fcffd4'},
{v:.66, hex:'#fff3a1'},
{v:.825, hex:'#ffa350'},
{v:1, hex:'#fb6252'},
]
stones.forEach(function(s){
s.rgb = hexToRgb(s.hex);
s.hsl = rgbToHsl.apply(0, s.rgb);
});
function valueToRgbColor(val){
for (var i=1; i<stones.length; i++) {
if (val<=stones[i].v) {
var k = (val-stones[i-1].v)/(stones[i].v-stones[i-1].v),
hsl = interpolArrays(stones[i-1].hsl, stones[i].hsl, k);
return 'rgb('+hslToRgb.apply(0,hsl).map(function(v){ return v|0})+')';
}
}
throw "bad value";
}
for (var i=0; i<=1; i+=.03) {
var color = valueToRgbColor(i);
$('<div>').css({background:color}).text(i.toFixed(2)+" -> "+color).appendTo('body');
}
body {
background: #222;
}
div {
width:200px;
margin:auto;
color: #333;
padding: 2px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For this example, I took the color space conversion functions here but there are easy to find once you know what to look for.
Note that modern browsers understand HSL colors (exemple: background: hsl(120,100%, 50%);) so, if you're just building HTML, you don't have to embed all this code in your page, just precompute the color stops and interpolate on the HSL values directly.
Here is one the solution in pure Javascript I just did. It process a linear interpolation between two colors.
/*
NASA color to RGB function
by Alexis Paques
It process a linear interpolation between two colors, here is the scheme:
0: blue
.165: blue white
.33: white
.495: yellow white
.66: yellow
.825: orange
1: red
*/
var blue = [0,0,255];
var bluewhite = [127,127,255];
var white = [255,255,255];
var yellowwhite = [255,255,127];
var yellow = [255,255,0];
var orange = [255,127,0];
var red = [255,0,0];
function color01toRGB(color01){
var RGB = [0,0,0];
var fromRGB = [0,0,0];
var toRGB = [0,0,0];
if(!color01)
return '#000000';
if(color01 > 1 || color01 < 0)
return '#000000';
if(color01 >= 0 && color01 <= 0.165 ){
fromRGB = blue;
toRGB = bluewhite;
}
else if(color01 > 0.165 && color01 <= 0.33 ){
fromRGB = bluewhite;
toRGB = white;
}
else if(color01 > 0.33 && color01 <= 0.495 ){
fromRGB = white;
toRGB = yellowwhite;
}
else if(color01 > 0.495 && color01 <= 0.66 ){
fromRGB = yellowwhite;
toRGB = yellow;
}
else if(color01 > 0.66 && color01 <= 0.825 ){
fromRGB = yellow;
toRGB = orange;
}
else if(color01 > 0.825 && color01 <= 1 ){
fromRGB = orange;
toRGB = red;
}
// 0.165
for (var i = RGB.length - 1; i >= 0; i--) {
RGB[i] = Math.round(fromRGB[i]*color01/0.165 + toRGB[i]*(1-color01/0.165)).toString(16);
};
return '#' + RGB.join('');
}
Since you have a list of values, all pretty well-saturated and bright, you can probably interpolate in the current (RGB) space for this. It won't be quite as pretty as if you convert to HSL, but will work fine for the colors you have.
Since you don't have any weighting or curves in the data, going with a simple linear interpolation should work just fine. Something like:
var stops = [
[0, 154, 175, 255],
[0.165, 202, 216, 255],
[0.33, 247, 247, 255],
[0.495, 252, 255, 212],
[0.66, 255, 243, 161],
[0.825, 255, 163, 80],
[1, 251, 98, 82]
];
function convertColor(color) {
var c = Math.min(Math.max(color, 0), 1); // Clamp between 0 and 1
// Find the first stop below c
var startIndex = 0;
for (; stops[startIndex][0] < c && startIndex < stops.length; ++startIndex) {
// nop
}
var start = stops[startIndex];
console.log('using stop', startIndex, 'as start');
// Find the next stop (above c)
var stopIndex = startIndex + 1;
if (stopIndex >= stops.length) {
stopIndex = stops.length - 1;
}
var stop = stops[stopIndex];
console.log('using stop', stopIndex, 'as stop');
// Find the distance from start to c and start to stop
var range = stop[0] - start[0];
var diff = c - start[0];
// Convert diff into a ratio from start to stop
if (range > 0) {
diff /= range;
}
console.log('interpolating', c, 'between', stop[0], 'and', start[0], 'by', diff);
// Convert from RGB to HSL
var a = rgbToHsl(start[1], start[2], start[3]);
var b = rgbToHsl(stop[1], stop[2], stop[3]);
console.log('hsl stops', a, b);
// Interpolate between the two colors (start * diff + (stop * (1 - diff)))
var out = [0, 0, 0];
out[0] = a[0] * diff + (b[0] * (1 - diff));
out[1] = a[1] * diff + (b[1] * (1 - diff));
out[2] = a[2] * diff + (b[2] * (1 - diff));
console.log('interpolated', out);
// Convert back from HSL to RGB
var r = hslToRgb(out[0], out[1], out[2]);
r = r.map(function(rv) {
// Round each component of the output
return Math.round(rv);
});
return r;
}
// Set the divs
var divs = document.querySelectorAll('.star');
Array.prototype.forEach.call(divs, function(star) {
var color = convertColor(star.dataset.color);
var colorStr = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
console.log('setting', star, 'to', colorStr);
star.style.backgroundColor = colorStr;
});
// HSL to RGB conversion from http://stackoverflow.com/a/30758827/129032
function rgbToHsl(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b),
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 [h, s, l];
}
function hslToRgb(h, s, l) {
var r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return [r * 255, g * 255, b * 255];
}
.star {
width: 24px;
height: 24px;
display: inline-block;
box-shadow: 0px 0px 16px -2px rgba(0, 0, 0, 0.66);
}
<div class="star" data-color="0.0"></div>
<div class="star" data-color="0.05"></div>
<div class="star" data-color="0.1"></div>
<div class="star" data-color="0.15"></div>
<div class="star" data-color="0.2"></div>
<div class="star" data-color="0.25"></div>
<div class="star" data-color="0.3"></div>
<div class="star" data-color="0.35"></div>
<div class="star" data-color="0.4"></div>
<div class="star" data-color="0.45"></div>
<div class="star" data-color="0.5"></div>
<div class="star" data-color="0.55"></div>
<div class="star" data-color="0.6"></div>
<div class="star" data-color="0.65"></div>
<div class="star" data-color="0.7"></div>
<div class="star" data-color="0.75"></div>
<div class="star" data-color="0.8"></div>
<div class="star" data-color="0.85"></div>
<div class="star" data-color="0.9"></div>
<div class="star" data-color="0.95"></div>
<div class="star" data-color="1.0"></div>

Smoothly fade image RGB by setting SRC data Javascript

I am working on emulating the behavior of the server box on https://mcprohosting.com/ but without sending multiple images (currently there are 3 images that rotate using javascripts .fadeout() calls and such.
My best attempt at doing this right now consists of parsing over the image pixels using HTML 5.
That being said there are a few problems:
I can't figure out how to smoothly transition between 3 preset colors.
The entire RGB spectrum is getting affected, whereas only the green colored section should be affected.
The logo is also being affected, how would I go about excluding this from the changed section? I presume I would have to manually specific the bounds of this element, but how would I do that specifically?
EDITED
I now convert RGB to HSL and vice-versa in order to do this change, the problem still lies in that the 'lightness' appears to be off. The dark parts of the server are too dark and lose detail
Here is the code:
<script type="text/javascript">
var mug = document.getElementById("server_green");
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;
function getPixels(img) {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
originalPixels = ctx.getImageData(0, 0, img.width, img.height);
currentPixels = ctx.getImageData(0, 0, img.width, img.height);
img.onload = null;
}
var t = 0;
function changeColor() {
//Checks if the image was loaded
if(!originalPixels) {
return;
}
//var blue = changeHue(rgbToHex(originalPixels.data[i], originalPixels.data[i + 1], originalPixels.data[i + 2]), t);
//var green = changeHue(rgbToHex(originalPixels.data[i], originalPixels.data[i + 1], originalPixels.data[i + 2]), t);
for(var i = 0, L = originalPixels.data.length; i < L; i += 4) {
var red = changeHue(originalPixels.data[i], originalPixels.data[i + 1], originalPixels.data[i + 2], t);
// If it's not a transparent pixel
if(currentPixels.data[i + 3] > 0 && originalPixels.data[i + 1] <= 255) {
currentPixels.data[i] = originalPixels.data[i] / 255 * red[0];
currentPixels.data[i + 1] = originalPixels.data[i + 1] / 255 * red[1];
currentPixels.data[i + 2] = originalPixels.data[i + 2] / 255 * red[2];
}
}
ctx.putImageData(currentPixels, 0, 0);
var data = canvas.toDataURL("image/png");
mug.src = data;
t += 10;
console.log("Running: " + t);
}
$(document).ready(function() {
setInterval(function() {
changeColor();
}, 10);
});
function changeHue(r, g, b, degree) {
var hsl = rgbToHSL(r, g, b);
hsl.h += degree;
if (hsl.h > 360) {
hsl.h -= 360;
} else if (hsl.h < 0) {
hsl.h += 360;
}
return hslToRGB(hsl);
}
function rgbToHSL(r, g, b) {
r = r / 255;
g = g / 255;
b = b / 255;
var cMax = Math.max(r, g, b),
cMin = Math.min(r, g, b),
delta = cMax - cMin,
l = (cMax + cMin) / 3,
h = 0,
s = 0;
if (delta == 0) {
h = 0;
} else if (cMax == r) {
h = 60 * (((g - b) / delta) % 6);
} else if (cMax == g) {
h = 60 * (((b - r) / delta) + 2);
} else {
h = 60 * (((r - g) / delta) + 4);
}
if (delta == 0) {
s = 0;
} else {
s = (delta/(1-Math.abs(2*l - 1)))
}
return {
h: h,
s: s,
l: l
}
}
function hslToRGB(hsl) {
var h = hsl.h,
s = hsl.s,
l = hsl.l,
//Chroma
c = (1 - Math.abs(2 * l - 1)) * s,
x = c * ( 1 - Math.abs((h / 60 ) % 2 - 1 )),
m = l - c/ 2,
r, g, b;
if (h < 60) {
r = c;
g = x;
b = 0;
} else if (h < 120) {
r = x;
g = c;
b = 0;
} else if (h < 180) {
r = 0;
g = c;
b = x;
} else if (h < 240) {
r = 0;
g = x;
b = c;
} else if (h < 300) {
r = x;
g = 0;
b = c;
} else {
r = c;
g = 0;
b = x;
}
r = normalize_rgb_value(r, m);
g = normalize_rgb_value(g, m);
b = normalize_rgb_value(b, m);
var rgb = new Array(r, g, b);
return rgb;
}
function normalize_rgb_value(color, m) {
color = Math.floor((color + m) * 255);
if (color < 0) {
color = 0;
}
return color;
}
</script>
And the resulting image (too dark) http://puu.sh/614dn/bf85b336ca.jpg
alternate solution (still using one image):
use a transparent png and + a coloring layer (beneath the png)
change the coloring layer's color with css transitions or javascript
The problem you are facing is caused by the color model, for instance white is made from red, green and blue. by adjusting the blue, you also affect the white.
you could use a solid chroma key to achieve the desired result, test the pixel for the key color and adjust if it's a match.
Here is a tutorial.

Turning RGB values into HSL values in a random Javascript

I have a random color overlay on the media-boxes of this site.
http://www.reportageborsen.se/reportageborsen/wordpress/
I had some really good help from the mates here at stackoverflow wich resulted in this script:
var getRandomInRange = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
$('.media-box').each(function() {
var mediaBox = $(this);
var mask = mediaBox.find('.mask');
var hue = 'rgb(' + getRandomInRange(100, 255) + ',' + getRandomInRange(100, 255) + ',' + getRandomInRange(100, 255) + ')';
mask.css({
backgroundColor : hue,
opacity : 0.7
});
mediaBox.hover(function() {
mask.stop(true, true).fadeIn();
}, function() {
mask.stop(true, true).fadeOut();
});
});​
Fiddle link: http://jsfiddle.net/b5ZPq/3/
However, I would love to have more of the brighter colors and less of the greyish ones. I understand that it can be done with HSL values instead of RGB values.
So I tried to convert the css background rgb values to hsl values and also converted the script, but I didn't get it to work.
var getRandomInRange = function(min, max) {
return Math.floor(Math.random() * (max - min + 1), 10) + min;
};
$('.media-box').each(function() {
var mediaBox = $(this);
var mask = mediaBox.find('.mask');
var hue = 'hsl(' + getRandomInRange(0, 360) + ',' + getRandomInRange(70, 100) + '%' + getRandomInRange(45, 55) + '%)';
mask.css({
backgroundColor: hue,
opacity: 0.7
});
mediaBox.hover(function() {
mask.stop(true, true).fadeIn();
}, function() {
mask.stop(true, true).fadeOut();
});
});​
http://jsfiddle.net/zolana/Kc9U4/5/
(the fiddle, updated, working:
http://jsfiddle.net/zolana/Kc9U4/9/
)
(I'm not looking for a script that converts all the RGB values to HSL values (I know there are scripts with that purpose) rather to have a solid script for this specific task.)
Remember that when you use HSL colors (and others), you need to separate each value with a comma and use the correct notation. In this case, it looks like the following.
hsl ( int hue , int saturation % , int lightness % )
You were missing a comma after the second argument (specifically right after the percent sign).
var hue = 'hsl(' + getRandomInRange(0, 360) + ',' + getRandomInRange(70, 100) + '%,' + getRandomInRange(45, 55) + '%)';
http://jsfiddle.net/b5ZPq/4/
Check out this code I wrote:
function randomColor(){
var h = Math.random();
var s = 0.99;
var v = 0.99;
h = h + 0.618033988749895;
h = h % 1;
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch(i % 6){
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return "rgba("+Math.floor(r*255)+","+ Math.floor(g*255)+","+ Math.floor(b*255)+","+ 0.2+")";
}
It generates a random Hue value, constant values for s and v. So this returns a random bright rgb color. Also the colors are bright and different because I have used the golden ratio. Try to use this and get back if you get any problems.

Categories

Resources