xxxxxxxxxx
70
let r, g, b;
let L1Picker,L2Picker;
// L = 0.2126 * r + 0.7152 * g + 0.0722 * b;
function setup() {
createCanvas(400, 400);
textAlign(CENTER);
L1Picker = createColorPicker("rgb(0,0,0)");
L2Picker = createColorPicker("#FFFFFF");
}
function draw() {
let L1 = L1Picker.value();
let L2 = L2Picker.value();
background(L1);
textSize(32);
noStroke();
fill(L2);
text("TEST", width / 2, height / 2);
fill(255);
noStroke();
rect(0, height-50, width)
fill(0);
noStroke();
textSize(22);
text('color contrast ratio is ' + Math.round(checkContrast(L1, L2) * 10) / 10 + ' : 1',
200,
height-20)
}
function luminance(r, g, b) {
let [lumR, lumG, lumB] = [r, g, b].map((component) => {
let proportion = component / 255;
return proportion <= 0.03928
? proportion / 12.92
: Math.pow((proportion + 0.055) / 1.055, 2.4);
});
return 0.2126 * lumR + 0.7152 * lumG + 0.0722 * lumB;
}
function contrastRatio(luminance1, luminance2) {
let lighterLum = Math.max(luminance1, luminance2);
let darkerLum = Math.min(luminance1, luminance2);
return (lighterLum + 0.05) / (darkerLum + 0.05);
}
function checkContrast(color1, color2) {
let [luminance1, luminance2] = [color1, color2].map((color) => {
/* Remove the leading hash sign if it exists */
color = color.startsWith("#") ? color.slice(1) : color;
let r = parseInt(color.slice(0, 2), 16);
let g = parseInt(color.slice(2, 4), 16);
let b = parseInt(color.slice(4, 6), 16);
return luminance(r, g, b);
});
return contrastRatio(luminance1, luminance2);
}