zoukankan      html  css  js  c++  java
  • JS多种方法实现随机颜色;

    JS随机颜色有很多地方要用到:比如大家看到很多标签连接都是五颜六色。实现随机颜色的方法有多种,下面来看看具体的实现代码:

    方法一:

    var getRandomColor = function() {
        
        return '#' +
            (function(color) {
                return (color += '0123456789abcdef' [Math.floor(Math.random() * 16)]) && (color.length == 6) ? color : arguments.callee(color);
            })('');
    }

    随机生成6个字符然后再串到一起,闭包调用自身与三元运算符让程序变得内敛;其实分解开来,代码相当于:

    function _g(color) {
    
        if ((color += '0123456789abcdef' [Math.floor(Math.random() * 16)]) && (color.length == 6)) {
            return color
        } else {
            return arguments.callee(color);
        }
    }
    var getRandomColor = function() {
        return '#' + _g('');
    }

    首先从getRandomColor函数里面传过来一个空字符串,首先连接上'0123456789abcdef'字符串里面随机的一个字母,也就是这段代码:color += '0123456789abcdef'[Math.floor(Math.random()*16)];

    然后判断color这个变量的长度是不是为6,因为标准的颜色值是一个长度为6的字符串,第一次执行为1,所以不满足,执行问号后面的arguments.callee(color);自调用;

    方法二:

    var getRandomColor = function() {
    
        return (function(m, s, c) {
            return (c ? arguments.callee(m, s, c - 1) : '#') +
                s[m.floor(m.random() * 16)]
        })(Math, '0123456789abcdef', 5)
    }

    把Math对象,用于生成hex颜色值的字符串提取出来,并利用第三个参数来判断是否还继续调用自身。

    方法三:

    //随机颜色,十六进制方法;
    function getRandomColor( ) {
        var rand = Math.floor(Math.random( ) * 0xFFFFFF).toString(16);
        if(rand.length == 6){
            return rand;
        }else{
            return getRandomColor();
        }
    }

    这个方法用到了十六进制与十进制的转换,我们熟知的颜色值比如#ffffff这种写法是十六进制颜色写法,将其转换为十进制之后得到16777215;转换代码如下:

    var a="#ffffff"
    console.log(parseInt(a.slice(1),16))   // ==> 16777215

    然后我们再将16777215转换为十六进制,可以得到ffffff,前面的#号在十六进制中就是0x,所以就有了上面代码中的0xFFFFFF了;

    var a=16777215
    console.log(a.toString(16))   // ==> ffffff

    方法四:HSL模式颜色随机;

    var getRandomColor = function() {
        return "hsl(" + Math.round(Math.random() * 360) + "," + Math.round(Math.random() * 100) + '%,' + Math.round(Math.random() * 100) + '%)';
    }

    方法五:RGB模式随机;

    var getRandomColor = function() {
        return "rgb(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + ',' + Math.round(Math.random() * 10) + ')';
    }

    方法六:RGB模式随机另外一种方法;

    var getRandomColor = function () {
        var r = Math.round(Math.random() * 255), g = Math.round(Math.random() * 255), b = Math.round(Math.random() * 255);
        var color = r << 16 | g << 8 | b;
        return "#" + color.toString(16)
    }
  • 相关阅读:
    YbtOJ20030 连珠风暴
    YbtOJ20029 最大权值
    P6859 蝴蝶与花
    P4115 Qtree4
    P2486 [SDOI2011]染色
    P2487 [SDOI2011]拦截导弹
    P5163 WD与地图
    P3733 [HAOI2017]八纵八横
    CF1100F Ivan and Burgers
    P1712 [NOI2016]区间
  • 原文地址:https://www.cnblogs.com/jone-chen/p/5254484.html
Copyright © 2011-2022 走看看