I am generating random color with JavaScript. How do I know if the color produced is dark/light?
My JavaScriptcodes I use
btn.addEventListener('click', e => {
const R = Math.floor(Math.random() * 256);
const G = Math.floor(Math.random() * 256);
const B = Math.floor(Math.random() * 256);
body.style.backgroundColor = `rgb(${R}, ${G}, ${B})`;
colorText.innerText = `R: ${R} \nG: ${G} \nB: ${B}`;
});
As Iłya Bursov pointed out, you can calculate the lightness component (L) in HSL. The calculation for this is just 0.2126 * r + 0.7152 * g + 0.0722 * b. Because this value is range from 0 to 255, you can define "light colors" as any color with HSL lightness in the upper half of that range (>128), and vice versa for darkness. Like this:
const btn = document.getElementById('btn');
const colorText = document.getElementById('colorText');
btn.addEventListener('click', e => {
const R = Math.floor(Math.random() * 256);
const G = Math.floor(Math.random() * 256);
const B = Math.floor(Math.random() * 256);
let light = 0.2126 * R + 0.7152 * G + 0.0722 * B > 128;
console.log(light)
document.body.style.backgroundColor = `rgb(${R}, ${G}, ${B})`;
colorText.innerText = `R: ${R} \nG: ${G} \nB: ${B}`;
});
<button id="btn">Button</button>
<br>
<span id="colorText"></span>
Related
I would appreciate any help. I want to change the text color of the button every time it is a darker background color. I have been trying other variations of the below code. I cant seem to get the newColor to work. Thanks in advance for your help.
const button = document.querySelector('button');
const h1 = document.querySelector('h1');
button.addEventListener('click', () => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
h1.innerText = newColor;
})
let newColor;
const randomColor = () => {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
newColor = r * 0.299 + g * 0.587 + b * 0.114
if(newColor > 186) {
newColor = 'black';
} else {
newColor = 'white';
}
return `rgb(${r}, ${g}, ${b})`;
}
I tried making my own function, I have tried putting an if statement on the outside of the function.
You can use the follow code:
var newRandomColor = Math.floor(Math.random()*16777215).toString(16)
This code works for generate random colors. Hope it helps you
For specifically an RGB color code you can use:
function RGBcolor() {
var R = Math.floor(Math.random() * 256);
var G = Math.floor(Math.random() * 256);
var B = Math.floor(Math.random() * 256);
var randomcolor = "rgb(" + R + "," + G + "," + B + ")";
console.log(randomcolor);
}
RGBcolor();
Hope it helps too!
Whenever I click a button on the browser it displays a random color along with its rgb(r,g,b) code. I made 3 variables r, g, and b which produce random numbers from 0 to 255 using the basic logic of Math.floor(Math.random()*256);
My problem is that sometimes the random colors generated are too dark and the rgb code displayed along with them is black in color.
I tried writing a logic that whenever r+g+b < 300, toggle the h1 element's class which has a property of color white.
const h1 = document.querySelector('h1');
const button = document.querySelector("button");
h1.classList.add('h1');
//if (r+g+b < 500)
button.addEventListener('click', () => {
changeColor();
});
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
h1.innerText = newColor;
}
);
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
})
A simple way is to make the r, g, b variables have a wider scope so they can be used to do your <500 test in the same place that you change the background color.
const h1 = document.querySelector('h1');
const button = document.querySelector("button");
let r, g, b;
h1.classList.add('h1');
button.addEventListener('click', () => {
changeColor();
});
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor;
if (r + g + b < 500) h1.style.color = 'white';
else h1.style.color = 'black';
h1.innerText = newColor;
});
const randomColor = (() => {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
})
<h1></h1>
<button>click me</button>
Try This:
const changeColor = (() => {
const newColor = randomColor();
document.body.style.backgroundColor = newColor[1];
h1.innerText = newColor[1];
const sumColor = newColor[0];
if (sumColor < 300){
h1.style.color = white;
}else{
h1.style.color = black;
}
}
);
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const sum = r+g+b;
return [sum,`rgb(${r}, ${g}, ${b})`]; //returning array
})
Well, you have to put your if inside this function (randomColor ) and when the values are generated for (r,g,b) you're if for the new values will be checked again every time the values change.
const randomColor = (() => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
if(r+g+b < 300){
h1.classList.add('h1');
}
return `rgb(${r}, ${g}, ${b})`;
})
https://codepen.io/fodi91/pen/ExNqGpY
First I click the random background every 4 seconds button, then I click the random background onclick button, but the interval doesn't stop. Why? How can I solve this?
let onClick = document.getElementById('generate');
onClick.addEventListener('click', generator);
let onClick2 = document.getElementById('generate2');
onClick2.addEventListener('click', generator2);
function generator2() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let background = document.getElementById('random');
background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
myInterval = setInterval(generator2, 2000);
}
function generator() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let background = document.getElementById('random');
background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
clearInterval(myInterval);
}
There are a couple of issues with your code.
Firstly, you need to declare your myInterval variable outside of the generator2() function.
The second issue is that your interval function is calling itself creating a recursive loop. Separate your callback which sets the interval from the code you want to execute on each interval.
let myInterval;
let onClick = document.getElementById('generate');
. . .
onClick2.addEventListener('click', secondClickHandler);
function secondClickHandler() {
myInterval = setInterval(generator2, 2000);
}
function generator2() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let background = document.getElementById('random');
background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
With that in mind, here's how I'd approach it:
const generate1Button = document.getElementById('generate');
const generate2Button = document.getElementById('generate2');
const randomBackground = document.getElementById('random');
let backgroundInterval;
generate1Button.addEventListener('click', () => {
clearInterval(backgroundInterval);
setRandomBackgroundColor();
})
generate2Button.addEventListener('click', () => {
setRandomBackgroundColor();
backgroundInterval = setInterval(setRandomBackgroundColor, 2000);
})
function setRandomBackgroundColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
randomBackground.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}
you have two problems:
You're using myInterval like it's a global variable, but it's not defined anywhere outside the functions
You're calling generator2 recursively, generator2 sets the color, then sets an interval to call generator2, regardless if there's another interval, so with every interval passing you actually set another interval, you'll eventually hang the tab with this. not to mention, myInterval will have a different interval ID, meaning even if you stop it, you only stopped the last running interval. a possible solution is setting the color changing to a different function, and have it called in the interval instead of on click.
The problem here is the fact that you are defining multiple intervals by calling the generator2 function in the interval itself. So instead, you should use a setTimeout. This would cause every timeout defined to get cleared (almost) as soon as the timer runs out.
So, the generator functions would change to:
function generator2() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let background = document.getElementById('random');
background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
myTimeout = setTimeout(generator2, 2000);
}
function generator() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let background = document.getElementById('random');
background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
clearTimeout(myTimeout);
}
In addition, you would have to ensure the myTimeout is declared such that it is accessible by the generator function as well, since you wish to clear it on the button click.
I would like to get random colors for each object in canvas how can i do that, I have tried this:
for (var i = 0; i < 100; i++) {
var raza = (Math.random() - 0.001) * 30;
var x = Math.random() * (innerWidth - raza * 2) + raza;
var y = Math.random() * (innerHeight - raza * 2) + raza;
var dx = (Math.random() - 0.5) * 4; //calcul viteza X
var dy = (Math.random() - 0.5) * 4; //calcul viteza Y
var color = c.strokeStyle = "#" + ((1 << 24) * Math.random() | 0).toString(12);
cercArray.push(new Circle(x, y, dx, dy, raza, color));
}
Lots of different ways to do this, here is an example using HSL.
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let lastDate = Date.now() - 500;
function draw() {
requestAnimationFrame(draw);
const color = {
h: Math.floor(Math.random() * 360),
s: Math.floor(Math.random() * 100),
v: Math.floor(Math.random() * 100)
};
if (lastDate + 500 < Date.now()) {
lastDate = Date.now();
ctx.fillStyle = `hsl(${color.h},${color.s}% ,${color.v}%)`;
ctx.fillRect(0, 0, 100, 100);
}
}
draw();
<canvas></canvas>
Hi there my problem with the code below is the the arc is creating 1 shape not the ten specified in the for loop...
If I was to change from arc to $cd.fillRect(10,20,$x,$y); then that would create 10 different rectangles but not the arc... what am I misunderstanding here?
var $canvas = $('#canvas-one')[0],
$cd;
if ($canvas.getContext) {
$cd = $canvas.getContext('2d');
for (i = 0; i <= 10; i++) {
$cd.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
$cd.strokeStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
var $x = 300 + Math.floor(Math.random() * 101);
var $y = 300 + Math.floor(Math.random() * 101);
var $radius = 0.1 + Math.floor(Math.random() * 6);
$cd.beginPath();
$cd.arc($x, $y, $radius, 0, Math.PI * 2, true);
}
$cd.stroke();
$cd.fill();
//$canvas.width = $canvas.height;
}
stroke and fill should be in the loop
I think you forgot to multiply x with i.
for (let i = 0; i < 10; i++) {
context.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
context.beginPath();
context.arc(i * x, y,15, 0, 2 * Math.PI,true);
context.fill();