JavaScript - 生成颜色
在 Web 开发项目中,生成颜色非常方便。为了获得美观的 UI,我们需要使用不同的颜色。在本章中,我们将学习如何使用 JavaScript 生成颜色。
生成随机十六进制颜色
十六进制 (Hex) 代码是一个六位数字和一个三字节的十六进制数,用于表示颜色。
这三个字节代表 RGB,即特定颜色中红色、绿色和蓝色的含量。每个字节代表 00 到 FF(十六进制表示法)或 0 到 255(十进制表示法)范围内的一个数字。这表示从 0 到 255 的每个颜色分量的强度。
以下是用于生成随机十六进制代码的函数
Math.random()
此函数用于随机获取 0 到小于 1 范围内的数字(包括小数)。
function random_num(maximum) {
return Math.floor(Math.random() * maximum);
}
document.write(random_num(5));
// 输出: 0, 1 or 2
在上面的代码片段中,我们输入的最大值是 5。每当我们尝试执行程序时,它都会打印 0 到 4 之间的输出。
document.write(random_num()); // 输出:0 到 1
在这种情况下,由于我们没有任何输入值作为最大值,因此每次运行程序时,它都会打印一个 0 到 1 之间的随机数。这就是 Math.random() 函数的工作原理。
Math.floor()
这是一个将数字向下舍入到最接近的整数的函数。
document.write(Math.floor(1.95)); // 输出:1
这里,我们可以看到输出结果为 5。因此,该值向下舍入为最接近的整数。
document.write(Math.floor(1)); // 输出:1
如果传递的值是完全整数,没有任何浮点(小数),则会进行四舍五入。
现在,让我们组合这些函数来生成随机十六进制数。
我们使用 math.random() 生成一个随机数,并将其与 16777215 相乘,因为这个数字是 fffff(十六进制代码中的最高位)的十进制表示。
Math.random()*16777215
这将返回一个带有小数的随机数,例如 12421420.464841081。现在我们使用 math.floor() 去除小数部分并返回一个整数。
Math.floor(Math.random()*16777215)
现在,我们引入 toString() 方法将数字转换为字符串。我们传入 16 作为参数,因为 16 是十六进制数。16 的值将返回十六进制代码(包含数字和字母)。
Math.floor(Math.random()*16777215).toString(16);
示例
现在,是时候生成随机十六进制颜色代码了。我们将使用上面的代码片段来生成随机十六进制颜色代码。
<!DOCTYPE html>
<html>
<title>Generating random hex color</title>
<head>
<h3>
<div id="demo">Mouse-over on this box to get new random color</div>
<p id="color"></p>
</h3>
<style>
body {
height: 100vh;
padding: 1rem;
display: grid;
place-items: center;
font-family: verdana;
}
h3 {
background: white;
padding: 1rem 1rem;
text-align: center;
border-radius: 5px 20px 5px;
}
p {
display: block;
padding: 1px;
font-size: 20px;
font-weight: lighter;
font-family: verdana;
}
</style>
</head>
<body>
<script>
function hex() {
const RanHexColor = '#' + Math.floor(Math.random()*16777215).toString(16);
document.body.style.backgroundColor = RanHexColor;
color.innerHTML = RanHexColor;
}
demo.addEventListener("mouseover", hex);
hex();
</script>
</body>
</html>
在输出中,每当鼠标悬停在中间的框上时,背景都会生成随机的十六进制颜色。
生成随机 RGB 颜色
在 JavaScript 中生成随机 RGB 颜色时,我们使用与十六进制颜色相同的技巧。我们将生成红色、绿色和蓝色的随机数,然后将它们组合起来得到 RGB 颜色。
示例
以下是生成随机 RGB 颜色的代码片段:
<!DOCTYPE html>
<html>
<title>Generating random RGB color</title>
<head>
<h3>
<div id="demo">Mouse-over on this box to get new random color</div>
<p id="color"></p>
</h3>
<style>
body {
height: 100vh;
padding: 1rem;
display: grid;
place-items: center;
font-family: verdana;
}
h3 {
background: white;
padding: 1rem 1rem;
text-align: center;
border-radius: 5px 20px 5px;
}
p {
display: block;
padding: 1px;
font-size: 20px;
font-weight: lighter;
font-family: verdana;
}
</style>
</head>
<body>
<script>
function rgb() {
const RanRGBColor = 'rgb(' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + ')';
document.body.style.backgroundColor = RanRGBColor;
color.innerHTML = RanRGBColor;
}
demo.addEventListener("mouseover", rgb);
rgb();
</script>
</body>
</html>
输出
在输出中,每当鼠标悬停在中间的框上时,背景上都会生成随机的 RGB 颜色。

