JavaScript Math Range的替代方案?

时间:2018-01-24 14:43:18

标签: javascript

我看到了将RGB颜色更改为RGBA的要点,但JS Math没有范围方法。有没有办法在这里转换范围方法?

function rgba(hex, opacity) {
    var colours = hex.regex(/#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})/i).map(function(val) {
        return Math.range(0, parseInt(val, 16), 255);
    }).join(",");
    if (opacity === undefined) {
        return "rgb(" + colours + ")";
    }
    return "rgba(" + colours + "," + opacity + ")";
}

在此处找到:https://gist.github.com/Rycochet/8597336

2 个答案:

答案 0 :(得分:2)

在我看来,range方法只是限制了价值。您可以通过合并maxmin方法来实现这一目标。

Math.range = function(min, val, max) {
  return Math.max(min, Math.min(val, max));
};

答案 1 :(得分:1)

在没有range

的情况下完成颜色转换
function rgba(hex, opacity) {
    var colours = hexToRgb(hex);
    if (opacity === undefined) {
        return "rgb(" + colours + ")";
    }
    return "rgba(" + colours + "," + opacity + ")";
}

function hexToRgb(hex) {
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return r + "," + g + "," + b;
}

函数hexToRgb(hex)来自RGB to Hex and Hex to RGB