Jump to content

Module:Color

From Voices of Democracy Wiki

Documentation for this module may be created at Module:Color/doc

local p = {}

function hex2rgb(hex)
    if not hex then return nil, nil, nil end
    hex = hex:gsub("#", "")
    if #hex == 3 then
        return tonumber("0x"..hex:sub(1,1)..hex:sub(1,1)),
               tonumber("0x"..hex:sub(2,2)..hex:sub(2,2)),
               tonumber("0x"..hex:sub(3,3)..hex:sub(3,3))
    elseif #hex == 6 then
        return tonumber("0x"..hex:sub(1,2)),
               tonumber("0x"..hex:sub(3,4)),
               tonumber("0x"..hex:sub(5,6))
    end
    return nil, nil, nil
end

function rgb2hex(r, g, b)
    return string.format("%02X%02X%02X", math.floor(r), math.floor(g), math.floor(b))
end

function p.hexMix(frame)
    local args = frame.args
    local color1 = args[1] or "FFFFFF"
    local color2 = args[2] or "000000"
    local value = tonumber(args[3]) or 0
    local max = tonumber(args.max) or 100

    local r1, g1, b1 = hex2rgb(color1)
    local r2, g2, b2 = hex2rgb(color2)

    if not r1 or not r2 then
        return "ERROR"
    end

    local ratio = math.min(math.max(value / max, 0), 1)

    local r = r1 * (1 - ratio) + r2 * ratio
    local g = g1 * (1 - ratio) + g2 * ratio
    local b = b1 * (1 - ratio) + b2 * ratio

    return rgb2hex(r, g, b)
end

return p