all files / src/creator/ hsla-creator.js

100% Statements 38/38
79.17% Branches 19/24
100% Functions 9/9
100% Lines 14/14
2 statements, 4 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                           62132× 62132× 62132× 62132× 62132× 62132× 62132×             62132×               186396× 62132×        
import { Color } from "../color";
 
/**
 * HSLA表現の作成処理を提供します。
 */
class HslaCreator {
    /**
     * 色表現を作成します。
     * @param {Color} color 生成元の色情報。
     * @return {String} 色表現。
     */
    create(color) {
        /* ---------------------------------------------------------------------- */
        // 30-seconds-of-code (Licensed under CC BY 4.0)
        // https://www.30secondsofcode.org/js/s/rgb-to-hsl
        const rgbToHsl = (r, g, b) => {
            r /= 255;
            g /= 255;
            b /= 255;
            const l = Math.max(r, g, b);
            const s = l - Math.min(r, g, b);
            const h = s
                ? l === r
                    ? (g - b) / s
                    : l === g
                    ? 2 + (b - r) / s
                    : 4 + (r - g) / s
                : 0;
            return [
                60 * h < 0 ? 60 * h + 360 : 60 * h,
                100 * (s ? (l <= 0.5 ? s / (2 * l - s) : s / (2 - (2 * l - s))) : 0),
                (100 * (2 * l - s)) / 2,
            ];
        };
        /* ---------------------------------------------------------------------- */
 
        const hsl = rgbToHsl(color.r, color.g, color.b).map(x => Math.round(x));
        return `hsla(${hsl[0]},${hsl[1]}%,${hsl[2]}%,${color.a != null ? Math.round(color.a) : 100}%)`;
    }
}
 
export { HslaCreator };