increase and decrease number in loop with logical operators - javascript

I was looking at this question and notice the way the loop
for( i=0; i < 1<<24; i++) {
r = (i>>16) & 0xff;
g = (i>>8) & 0xff;
b = i & 0xff;
colour = "rgb("+r+","+g+","+b+")";
}
increases the numbers and then "stuck" them to 0 with & 0xFF
So basically as I understood the value of, e.g, b will increase till it's 255 and then will result always 0.
I was wondering if there is a similar way to let the value of a variable increase to 255 and then decrease gradually from 255 to 0.
loop execution example of what I mean:
...
255, 254, 0
255, 255, 0
255, 254, 0
255, 253, 0
...
255, 2, 0
255, 1, 0
255, 0, 0

Related

How to find the index of the center element of a 2d array using javascript?

Let's say we have an image which a 2d array like this:
var img = [
[
{ r: 255, g: 255, b: 255 },
{ r: 255, g: 255, b: 255 },
{ r: 255, g: 255, b: 255 }
],
[
{ r: 255, g: 255, b: 255 },
{ r: 255, g: 255, b: 255 },
{ r: 255, g: 255, b: 255 }
],
[
{ r: 255, g: 255, b: 255 },
{ r: 255, g: 255, b: 255 },
{ r: 255, g: 255, b: 255 }
]
];
We have a 3x3 matrix. Each record represents a pixel.
Now the middle element is the fifth record or Img[1][1].
I want to be able to find the index of the middle element in any odd number square matrix. How can I do this?
I have tried thinking about this and thought about using the modulus operator.
We would have let's a 5x5 matrix which means 25 pixels. I would then try to divide 25 by 2:
25/2 = 12 with a remainder 25 mod 2 = 1.
Therefore the middle element would be 12 + 1 = 13.
Because we have a 5x5 matrix this means that each line in the matrix contains 5 elements.
We would have to do:
13/5 = 2 meaning we have to go through 2 lines of 5. Which mean we can skip directly from img[0][x] , img[1][x] to [2][x]. (Skipping to the third line)
13 mod 5 = 3 to get the index inside the line we're in meaning img[2][3] but this is wrong because 13 would be in the third spot but with index 2 because 0,1,2 so we would have img[2][2].
Doing for 7x7 matrix I notice a pattern for 3x3 we had img[1][1], for 5x5 we had img[2][2], for 7x7 we have img[3][3].
So my trouble with all of this is I do not now for sure if it applies for all even numbers and how to translate it to a javascript code.
const row = img[Math.floor(img.length / 2)];
const result = row[Math.floor(row.length / 2)];
No need for modulo here

How to convert transparent colors to rgb

I have colors in following format
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
They are transparent colors, but when i convert them to this:
backgroundColor: [
getRandomColor(),
getRandomColor(),
],
They are not transparent anymore.
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
Can anyone help me please thanks.
You should probably stick to the rgba format you originally used because you can't specify the alpha channel using the hex notation. So your code would have to go through another run just to convert it back from hex to rgba and add the alpha value.
See this example, it randomizes all four (rgba) components:
function getRandomColor() {
var color = [];
for (var i = 0; i < 3; i++ ) {
color.push(Math.floor(Math.random() * 256));
}
color.push(Math.random()); // alpha
return 'rgba(' + color.join(',') + ')';
}
div {text-align: center; margin: 20px 0; font-size: 40px;text-shadow: 0 0 1px #000; color: #ff0;cursor:pointer}
div:hover {text-shadow: 0 0 1px #000, 0 0 2px #000, 0 0 4px #000}
body {background: url(https://thumbs.dreamstime.com/x/retro-tile-background-5479386.jpg)}
<div onclick="this.style.background = getRandomColor()">Click me</div>
Of course, you can modify it to randomize only the RGB components and add alpha manually in case you want it locked at 0.2.
How to convert transparent colors to rgb?
here's a function that should work in converting rgba to rgb:
var backgroundColor = [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
]
function RGBfromRGBA(rgba) {
const [r, g, b, per] = rgba.match(/[0-9\.]+/g)
const diff = Number(per)
return `rgb(${ channelInter(Number(r),diff) },${channelInter(Number(g),diff) },${channelInter(Number(b),diff)})`
}
function channelInter(v, p) {
return 255 - (255 - v) * p | 0
}
var res = RGBfromRGBA(backgroundColor[1])
$('#rgba').css('background', backgroundColor[1]).html(backgroundColor[1])
$('#rgb').css('background', res).html(res)
div {
height: 100px;
width: 100px;
margin: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='rgba'></div>
<div id='rgb'></div>
in the snippet I also made a little test and it seems ok, let me know how it goes;
HEX (example): #42dff4 NOT transparent
RGB (example): rgb(100,42,230) NOT transparent
RGBA (example): rgba(123,42,243,0.5) Transparent
getRandomColor() returns colors in HEX value. HEX values are always non-transparent. If you want random rgba color values (transparent) do this:
function getRandomColor() {
return "rgba(" + Math.floor(Math.random() * 255) + ","
+ Math.floor(Math.random() * 255) + ","
+ Math.floor(Math.random() * 255) + ",0.2)";
}
This will return a rgba value, this is the code you are looking for.
You just have to return 3 different value for red, green, blue between 0 and 255....
edit : And use rgba, for specify the opacity of the color.
rgba(red,green,blue,alpha=opacity).
function getRndColor()
{
return "rgba("+Math.floor(Math.random()*255)+","+Math.floor(Math.random()*255)+","+Math.floor(Math.random()*255)+",0.2)";
}
console.log(getRndColor());

Convert dominant color with selected color

After working/studying hours with canvas i have managed to get the image clone and it's pixels now i have made the user select a color from a color specterm and i have that color hex in my function :
move: function (color) {
// 'color' is the value user selected
var img_id = jQuery(".selected_bg_img").attr("id");
alert(img_id);
var x = 0;
var y = 0;
var width = 409;
var height = 409;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById(img_id);
ctx.drawImage(img,x,y,width,height);
var imageData = ctx.getImageData(0,0,width,height);
var data = imageData.data;
alert(data);
}
now two tasks are getting in way,
1. How do we extract the maximum color from data ?
2. How do we convert that maximum color to the color we got in function ?
for live working example i have link given at end
NOTE: Select the images (any last 3) from left side of the product image and and when color is choose it clones the image to the canvas below.
Here i am trying to clone the image with replacement of maximum color with the color user selected.
NOTE: Maximum color i mean (dominant color in image), e.g http://lokeshdhakar.com/projects/color-thief/ this project is getting the dominant color of image but it's on node and i'm trying to get the dominant and to change that color before cloning too .
for (var i=0;i<imgData.data.length;i+=4)
{
imgData.data[i]=255-imgData.data[i];
imgData.data[i+1]=255-imgData.data[i+1];
imgData.data[i+2]=255-imgData.data[i+2];
imgData.data[i+3]=255;
}
*****EDIT*****
My problem is not very complex i think i have this image
so we can see clearly that the dominant color is grey, by any method i am just trying to replace that color with the new color i have in my function move and draw that image with the new color. The image from where i have taken and shows another example :
http://www.art.com/products/p14499522-sa-i3061806/pela-silverman-colorful-season-i.htm?sOrig=CAT&sOrigID=0&dimVals=729271&ui=573414C032AA44A693A641C8164EB595
on left side of image when we select the similar image they have option "change color" at the bottom center of image. This is what exactly i'm trying to do.
So now i tried to read the image 1x1 and this is what i get in the console when i log it(particular for the image i have shown) :
[166, 158, 152, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…]
So it maybe the very first start from top left corner, i guess it need to be iterated over whole image and this is what i get when i iterated over whole image:
[110, 118, 124, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255…]
The loop i used for iteration is:
var imageData = ctx.getImageData(0,0,width,height);
var data = imageData.data;
for (var i=0;i<data.length;i+=4)
{
data[i]=255-data[i];
data[i+1]=255-data[i+1];
data[i+2]=255-data[i+2];
data[i+3]=255;
}
console.log(data);
Is this iteration right ? If yes, it seems to be now matter of replacing the dominant color and i'm blank here how do we replace it and write back image with the replaced color or is there something more ?
*************EDIT***********
i have now user value in rgb, need to look for places where that value should be placed
This answer may be what you want as it is a little unclear.
Finding the dominant colour in an image
There are two ways that I use. There are many other ways to do it, which is the best is dependent on the needs and quality requiered. I will concentrat on using a histogram to filter out irrelevent pixels to get a result.
The easy way.
Create a canvas that is 1 by 1 pixel. Ensure that canvas smoothing is on.
ctx.imageSmoothingEnabled = true;
ctx.mozImageSmoothingEnabled = true;
The draw the image onto that 1 by 1 canvas
ctx.drawImage(image,0,0,1,1);
Get the pixel data
var data = ctx.getImageData(0,0,1,1);
And the rgb values are what you are after.
r = data.data[0];
g = data.data[0];
b = data.data[0];
The result applied to the image below.
The long way
This method is long and problematic. You need to ignore the low and high values in the histogram for rgb (ignore black and white values) and for HSL ignore Saturations and Values (Lightness) that are 0 or 100% or you will get reds always dominating for images that have good contrast.
In image processing a histogram is a plot of the distribution of image properties (eg red green blue) within the image. As digital images have discrete values the histogram (a bar graph) will plot along the x axis the value and in the y axis the number of pixels that have that value.
An example of the histogram. Note that this code will not run here as there is cross origin restriction. (sorry forgot my browser had that disabled).
/** CopyImage.js begin **/
// copies an image adding the 2d context
function copyImage(img){
var image = document.createElement("canvas");
image.width = img.width;
image.height = img.height;
image.ctx = image.getContext("2d");
image.ctx.drawImage(img, 0, 0);
return image;
}
function copyImageScale(img,scale){
var image = document.createElement("canvas");
image.width = Math.floor(img.width * scale);
image.height = Math.floor(img.height * scale);
image.ctx = image.getContext("2d");
image.ctx.drawImage(img, 0, 0,image.width,image.height);
return image;
}
/** CopyImage.js end **/
function getHistogram(img){ // create a histogram of rgb and Black and White
var R,G,B,BW;
R = [];
G = [];
B = [];
BW = []; // Black and white is just a mean of RGB
for(var i=0; i < 256; i++){
R[i] = 0;
G[i] = 0;
B[i] = 0;
BW[i] = 0;
}
var max = 0; // to normalise the values need max
var maxBW = 0; // Black and White will have much higher values so normalise seperatly
var data = img.ctx.getImageData(0,0,img.width,img.height);
var d = data.data;
var r,g,b;
i = 0;
while(i < d.length){
r = d[i++]; // get pixel rgb values
g = d[i++];
b = d[i++];
i++; // skip alpha
R[r] += 1; // count each value
G[g] += 1;
B[b] += 1;
BW[Math.floor((r+g+b)/3)] += 1;
}
// get max
for(i = 0; i < 256; i++){
max = Math.max(R[i],G[i],B[i],max);
maxBW = Math.max(BW[i],maxBW);
}
// return the data
return {
red : R,
green : G,
blue : B,
gray : BW,
rgbMax : max,
grayMax : maxBW,
};
}
function plotHistogram(data,ctx,sel){
var w = ctx.canvas.width;
var h = ctx.canvas.height;
ctx.clearRect(0,0,w,h); // clear any existing data
var d = data[sel];
if(sel !== "gray"){
ctx.fillStyle = sel;
}
var rw = 1 / d.length; // normalise bar width
rw *= w; // scale to draw area;
for(var i = 0; i < d.length; i++ ){
var v = 1-(d[i]/data.rgbMax); // normalise and invert for plot
v *= h; // scale to draw area;
var x = i/d.length; // normaise x axis
x *= w; // scale to draw area
if(sel === 'gray'){
ctx.fillStyle = "rgb("+i+","+i+","+i+")";
}
ctx.fillRect(x,v,rw,h-v); // plot the bar
}
}
var canMain = document.createElement("canvas");
canMain.width = 512;
canMain.height = 512;
canMain.ctx = canMain.getContext("2d");
document.body.appendChild(canMain);
var ctx = canMain.ctx;
var can = document.createElement("canvas");
can.width = 512;
can.height = 512;
can.ctx = can.getContext("2d");
// load image and display histogram
var image = new Image();
image.src = "http://i.stack.imgur.com/tjTTJ.jpg";
image.onload = function(){
image = copyImage(this);
var hist = getHistogram(image);
// make background black
ctx.fillStyle = "black"
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
// create and show each plot
plotHistogram(hist,can.ctx,"red");
document.body.appendChild(copyImageScale(can,0.5));
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"green");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "lighter"
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"blue");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "lighter"
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"gray");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "source-over"
ctx.globalAlpha = 0.9;
ctx.drawImage(can,0,0,canvas.width,canvas.height);
ctx.globalAlpha = 1;
}
As the above code required a hosted image the results are shown below.
The image
The RGB and gray histograms as output from above code.
From this you can see the dominant channels and the distribution of rgb over the image (Please note that I removed the black as this image has a lot of black pixels that where make the rest of the pixel counts shrink into insignificance)
To find the dominant colour you can do the same but for the HSL values. For this you will need to convert from RGB to HSL. This answer has a function to do that. Then it is just a matter of counting each HSL value and creating a histogram.
The next image is a histogram in HSL of the above sample image.
As you can see there is a lot of red, then a peek at yellow, and another in green.
But as is this still will not get you what you want. The second histogram (saturation) shows a clear peak in the center. There are a lot of colours that have good saturation but this does not tell you what colour that is.
You need to filter the HSL value to around that peak.
What I do is multiply the HSL values by the f(s) = 1-Math.abs(s-50)/50 s is Saturation range 0-100. This will amplify hue and value where saturation is max. The resulting histogram looks like
Now the peak hue (ignoring the reds) is orange. The hue value is ~ 42. Then you apply a filter that removes all pixels that are not near the hue = 42 (you may want to give a falloff). You apply this filter on the HSL value you get after the last step. The next image shows the resulting image after applying this filter to the original
and then get a sum of all the remaining pixel's R,G,B. The mean of each RGB value is the common colour.
The common colour as by this method.
Note the result is different than if you apply this method as described and in the code above. I used my own image processing app to get the instrume steps and it uses true logarithmic photon counts for RGB values that will tend to be darker than linear interpolation. The final step expands the filtered pixel image to an instrume step that is too complicated to describe here (a modification on the easy method at start of answer). looks like
Also I applied this to the whole image, this can be very slow for large images, but it will work just as well if you first reduce the size of the image (must have image smoothing on (defaults of most browsers)). 128 8 128 is a good size but you can go down lower. It will depend on the image how small you can make it befor it fails.

Getting value of individual box-shadow when set to multiple values

Trying to get an answer to a recent question, I tried to parse the box-shadow of an element, that had been set as
div {
box-shadow: 0 0 0 5px green, 0 0 0 10px #ff0000, 0 0 0 15px blue;
}
I expected to get that string, do an split(",") on it, and get the array of box-shadows. (with 3 elements)
My problem is that I get the string as
"rgb (0, 255, 0) 0 0 0 5px, rgb (255, 0, 0) 0 0 0 10px, rgb (0, 0, 255) 0 0 0 15px"
And of course when I split that I get a mess.
Is there an easier way to get the values of the individual box-shadows ?
you can try three separate statments
document.getElementById('the-element-id').style['boxShadow']
or do the split but use "px, " as the separator and add the "px" back to all values of the array except the last one
var string ="rgb (0, 255, 0) 0 0 0 5px, rgb (255, 0, 0) 0 0 0 10px, rgb (0, 0, 255) 0 0 0 15px";
var array= string.split("px, ");
var length = array.length;
for (var i=0; i<length; i++) {
if (i != length - 1){
array[i] = array[i] + "px";
}
console.log(array[i]);
}
jsFiddle
[EDIT]
I just realized this won't work if the last value of the box shadow is 0 (ie 15px 0 0 0, rgb)
here's the alternative in that case split on ", rgb" and add "rgb" back to all the values of the array except the first one:
var string ="rgb (0, 255, 0) 0 0 0 5px, rgb (255, 0, 0) 0 0 0 10px, rgb (0, 0, 255) 0 0 0 15px";
var array= string.split(", rgb");
for (var i=0; i<array.length; i++) {
if (i != 0 ){
array[i] = "rgb" + array[i];
}
console.log(array[i]);
}
jsFiddle

Run trough one rgba to another based on percentage

Let's say i have this both rgba codes:
rgba(150, 160, 255, 1) and rgba(195, 0, 0, 1)
I want to pass from one to another by a 0/100 percentage.
0% will be rgba(150, 160, 255, 1)
100% will be rgba(195, 0, 0, 1)
I'm trying to make a HeatMap with this.
How can i determinate what rgba will be at let say... 30%!?
For each value x in your code:
x = min_x + (max_x - min_x)*percentage/100
(Note: max_x can be smaller than min_x)
For each component, you just have to do start+(end-start)*percentage
So for your 30% you'd have:
red = 150 + (195 - 150) * 0.3 = 205.5
green = 160 + (0 - 160) * 0.3 = 112
blue = 255 + (0 - 255) * 0.3 = 178.5
alpha = 1 + (1 - 1) * 0.3 = 1
Your final colour will therefore be rgba(206, 112, 179, 1)

Categories

Resources