8/26/2023 0 Comments Random color generator javascriptIn this case, the padStart method will add 0 to the beginning of the randomNumber until length becomes 6. Imagine that the generated randomNumber is 123b, and the length of 123b is less than 6. Let randColor = randomNumber.padStart(6, 0) RandomNumber = randomNumber.toString(16) If the string length is less than 6, the padStart/padEnd will add the filler values we passed to the function: let maxVal = 0xFFFFFF // 16777215 In this article, I want to share about how to make your own random color generator using Vanilla JavaScript. In that case, we can use padStart or padEnd to ensure that the string length is at least 6. Generating random colors by just using Math.random values often results in dark and unattractive colors. The code above will generate a random color but, there may be a chance that the string length will be less than 6. Let randColor = randomNumber.toString(16) Let randomNumber = Math.random() * maxVal Now, that we have a random number generated for the hex, let’s convert that integer into hex again using the toString(16) method: let maxVal = 0xFFFFFF // 16777215 convert the floating-point number to an integer Let randomNumber = Math.random() * maxVal // returns a floating point random number Let’s create a random number from this maxVal: let maxVal = 0xFFFFFF // 16777215 In JavaScript, we add 0x before a hexadecimal number: let testHexVal = 0xff // 255 So, the maximum value can be FFFFFF - white color, and the minimum value can be 000000 - black color. The value of the Hexadecimal can range from 00 to FF. Works directly from your browser without any additional installation. A hexadecimal color can be represented as #RRGGBB: Use our FREE HTML/CSS/JavaScript online editor to write, run and share your code.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |