生成随机颜色的两种写法

616 阅读1分钟

想要写出随机颜色,首先得理解产生随机数的原理

    Math.random():一个浮点型伪随机数字,在`0`(包括0)和`1`(不包括)之间。[0,1)
    Math.floor():向下取整,比如说Math.floor(4.6)等于4
    产生一个0-16随机整数的写法:Math.floor(Math.random()*17)

一.十六进制随机颜色

 //1.十六进制随机颜色 格式:#0f2e30
    //将0-f存入数组中
    let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    let str = '#'
    //产生6个随机数拼接在 '#' 后面
    for (let i = 0; i < 6; i++) {
      let random = Math.floor(Math.random() * arr.length)
      str += arr[random]
    }
    //输出
    console.log(str)

每次刷新页面会输出不同的结果:#16f52d

二.rgb随机颜色 格式:rgb(255,255,255)

 //产生3个0-255的数组存在变量r,g,b中
    //注意:因为floor是下取整,最大值是255,所以Math.random()*(255+1)
    let r = Math.floor(Math.random() * 256)
    let g = Math.floor(Math.random() * 256)
    let b = Math.floor(Math.random() * 256)

    let rgb = `rgb(${r},${g},${b})`
    //输出
    console.log(rgb)

全部代码

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>


  <script>
    Math.floor()

    //1.十六进制随机颜色 格式:#0f2e30
    //将0-f存入数组中
    let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    let str = '#'
    //产生6个随机数拼接在 '#' 后面
    for (let i = 0; i < 6; i++) {
      let random = Math.floor(Math.random() * arr.length)
      str += arr[random]
    }
    //输出
    console.log(str)

    //2.rgb随机颜色 格式:rgb(255,255,255)
    //产生3个0-255的数组存在变量r,g,b中
    //注意:因为floor是下取整,最大值是255,所以Math.random()*(255+1)
    let r = Math.floor(Math.random() * 256)
    let g = Math.floor(Math.random() * 256)
    let b = Math.floor(Math.random() * 256)

    let rgb = `rgb(${r},${g},${b})`
    //输出
    console.log(rgb)

    //将颜色加给body
    document.body.style.backgroundColor = rgb

  </script>
</body>

</html>