I am trying to get something like this:
rbg(random, random, random);
Now when I put in Math.floor(Math.random() * 255) + 1 into the area, it works but for some reason most of the numbers are stuck in 255 and rarely change.
My code is:
function colorGen() {
document.getElementById("color1").style.backgroundColor = 'rgb('+
Math.floor(Math.random() * 255) + 1 + ',' + Math.floor(Math.random() * 255) + 1
+',' + Math.floor(Math.random() * 255) + 1 +')';
}
When I put brackets () around - ( Math.floor(Math.random() * 255) + 1 ) -, it works much better.
Why is this so?
#Xufox has the right answer in the comment there. For clarity, you'll want to restructure your code a little (and let's also fix that bug where you'll never get zero for any channel due to the +1):
function colorGen() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
document.getElementById("color1").style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")";
}
When you use +1 inside a string it will generate as string and not as mathematical expression when you use () it generate as mathematical expression.
My reccomand:
Use params to random colors
function colorGen() {
var color1=Math.floor(Math.random() * 255) + 1;
var color2=Math.floor(Math.random() * 255) + 1;
var color3=Math.floor(Math.random() * 255) + 1;
document.getElementById("color1").style.backgroundColor = 'rgb('+ color1
+ ',' + color2
+',' + color3 +')';
}
<button id="color1" onclick="colorGen()">click me to change color</button>
When you “add” 1, it gets concatenated as a string, since you’re starting with "rgb(" +, and the result of “string + number” will be another string. Wrapping numerical expressions in parentheses makes the + operator do addition instead of concatenation.
The reason you get 255 is because the numbers you generate end up looking like this:
11
21
31
41
…
2531
2541
2551
The backgroundColor setter caps 8-bit values (ranging from 0 to 255) at a maximum of 255 (and a minimum of 0). This means, setting element.style.backgroundColor = "rgb(10000, -10000, 128)" results in a backgroundColor of "rgb(255, 0, 128)"
So when Math.floor(Math.random() * 255) generates a number from 1 to 25, then the highest resulting number becomes 251, which is below 255. Any other value — i.e. from 26 to 255 — results in a value higher than 255, so it just becomes 255 automatically.
The parentheses make the arithmetic expression to be evaluated before the concatenation.
Related
I'm making a color game via a course which generates 6 squares with random colours. When you click on a square which corresponds with the target color, you win the game.
Here's a link to how the game should work using RGB:
https://jsfiddle.net/jdwrgbh0/
I'm using HSL values instead.
Here's my code using HSL:
https://jsfiddle.net/fh7boykd/
(The only difference is this code for generate random colors)
function randomColor() {
var h = Math.floor(Math.random() * 361);
var s = Math.floor(Math.random() * 101);
var l = Math.floor(Math.random() * 101);
return "hsl(" + h + ', ' + s + '%' + ', ' + l + '%' + ")";
}
Even though I used the function above to generate HSL values, the background-color of the squares still shows RGB values instead of HSL values and as such, I can't win the game because the target color is never shown. I want the color of the squares to display background-color in HSL and not RGB. The above randomColor function seems fine and testing it in the console, it does seem to generate a random color after it's invoked each time.
Here's an image of the console when I run the code. The background-color is in RGB and not HSL.
I think the problem may be related to this function:
function changeColors(color){
//loop through all squares
for(var i = 0; i < squares.length; i++){
//change each color to match given color
squares[i].style.background = color;
}
}
This code changes the color of each square. When I look at the browser console, it shows RGB values instead of HSL values. How do I force squares[i].style.background = color; to use HSL instead of RGB?
The browser will convert your HSL back to RGB colors. From what I see in your question, you are using HSL just so you can generate random colors. You can also use this piece of code to generate random hex color code
var generateRandomHexColor = () => {
var allPossibleLetters = '0123456789ABCDEF';
var HexCode = '';
for (var i = 0; i < 6; i++) {
HexCode += allPossibleLetters[Math.floor(Math.random() * 16)];
}
return '#' + HexCode;
}
console.log(generateRandomHexColor())
I believe your question is that you want to be able to convert RGB to HSL and then understand that HSL value. This is entirely possible. I have found some js script off of github, from user mjackson.
/**
* 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 ];
}
You may be able to adapt this to the way that you wish. I hope this helped.
Cheers!
if you want to set as hsl, just like this format:
divElement.style.backgroundColor = "hsl(155,100%,30%)";
but you want to got the style, that must be rgb or rgba string. so you must change it to hsl by your self.
This is a javascript function to generate r g b values for the chart color in my application
dynamicColors(index:number) {
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
};
This will random r,g,b value each time.
I have an index value as input I'm trying to generate a constant color for each index on each time.
If index is 1 ..then the r,g,b generated value should be same all the time, now its random each time.
Tried with Math.sin(), but didn't get expected result.
This question already has answers here:
Random color generator
(64 answers)
Closed 8 years ago.
I have this code that uses RGB color selection and I was wondering how to make JavaScript do a random color using the RGB method and remember it throughout the code.
EDIT: I tried this:
var RGBColor1 = (Math.round, Math.random, 255)
var RGBColor2 = (Math.round, Math.random, 255)
var RGBColor3 = (Math.round, Math.random, 255)
but it doesn't work. Help please!
EDIT 2: The code uses this:
g.fillStyle="rgba(R,G,B,0.2)";
g.strokeStyle="rgba(R,G,B,0.3)";
E();
The letters represent the color of RGB.
EDIT 3: The doubles of this question are using HEX values, not RGB values.
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
var color = random_rgba();
g.fillStyle = color;
g.strokeStyle = color;
FIDDLE
const randomBetween = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
const r = randomBetween(0, 255);
const g = randomBetween(0, 255);
const b = randomBetween(0, 255);
const rgb = `rgb(${r},${g},${b})`; // Collect all to a css color string
Here's a very simple method that works off of a single random number generation. Basically, it generates a number between 0 and 0xfffff (or 2^24, the highest number you can get from 24 bits). The highest value you can get from 8 bits is 255. This algorithm takes the left-most 8 bits of the random number for RED, the middle 8 bits for GREEN, and the last 8 bits for BLUE, using all 24 bits of the random number.
function getRandomRgb() {
var num = Math.round(0xffffff * Math.random());
var r = num >> 16;
var g = num >> 8 & 255;
var b = num & 255;
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
for (var i = 0; i < 10; i++) {
console.log(getRandomRgb());
}
Console output (sample):
rgb(2, 71, 181)
rgb(193, 253, 111)
rgb(172, 127, 203)
rgb(203, 53, 175)
rgb(226, 45, 44)
rgb(102, 181, 19)
rgb(92, 165, 221)
rgb(250, 40, 162)
rgb(250, 252, 120)
rgb(67, 59, 246)
Adapted from source.
I found on stackoverflow this color generator :
Math.random()*0xFFFFFF<<0
It works fine. The only problem is that I'd like to generate random colors, but only of different shades of grey.
I have no idea how I could achieve something like this.
var value = Math.random() * 0xFF | 0;
var grayscale = (value << 16) | (value << 8) | value;
var color = '#' + grayscale.toString(16);
color will be a random grayscale hex color value, appropriate for using in eg element.style properties.
Note: there are several ways to coerce the random floating-point number to an integer. Bitwise OR (x | 0) will usually be the fastest, as far as I know; the floor function (Math.floor(x)) is approximately the same speed, but only truncates for positive numbers (you'd have to use Math.ceil(x) for negative numbers). Bitwise operators won't work as expected for numbers that require more than 32 bits to represent, but Math.random() * 0xFF will always be in the range [0,255).
If you want to use RGB, rgb grays can be created by supplying the same number in all three arguments i.e. rgb(255,255,255) (the number must be between 0 and 255).
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var randomNumberString = String(getRandomInt(0,255));
var color = "rgb(" + randomNumberString + "," + randomNumberString + "," + randomNumberString + ")";
I'm sure this must be a fairly straightforward, but it's a difficult question to word. I don't even know what to google for.
I'm not looking for any complicated solution. Basically, I'm drawing lines on a Canvas, and I want different colours depending on the length of the line. Usually I just scale, say, the red channel (#ff0000 * (length of line)/(maximum line length)), but this solution isn't ideal. I'm just looking for an equation that will give me a #rrggbb value for a certain position on a rainbow gradient, if that makes sense.
Thank you to whoever can help with this! It's very much appreciated.
Since you're using canvas then you can probably use the HSL color space (correct me if I'm wrong). It would make the code much simpler:
function rainbow(n) {
n = n * 240 / 255;
return 'hsl(' + n + ',100%,50%)';
}
If you're ok with having your range from 0 to 240 then you can even remove the first line of this function. See DEMO.
This article describes a method to make rainbow colors in JS. Basically it uses the Sine function to make rainbow colors. In short, the equation you need is something like this. See DEMO.
function RainBowColor(length, maxLength)
{
var i = (length * 255 / maxLength);
var r = Math.round(Math.sin(0.024 * i + 0) * 127 + 128);
var g = Math.round(Math.sin(0.024 * i + 2) * 127 + 128);
var b = Math.round(Math.sin(0.024 * i + 4) * 127 + 128);
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
I ended up using something similar to #rsp 's answer
var getColorAtScalar = function (n, maxLength) {
var n = n * 240 / (maxLength);
return 'hsl(' + n + ',100%,50%)';
}