Light text over a light image is a familiar readability failure, and the usual remedy — a semi-transparent overlay — raises its own question: how transparent should it be? There is no single answer, because font sizes, weights, and colors vary, and every image changes the contrast picture. Guessing produces a game of Whac-a-Mole. HTML <canvas> plus a little math yields a definitive value instead.
The target is the WCAG definition of AA-level readability: text and background must contrast enough that one color is 4.5 times lighter than the other. Pick a text color, a background image, and an overlay color; the job is to find the overlay opacity that makes the text readable without obscuring the image too much. An image containing both dark and light areas must be accounted for. The output is a value for the CSS opacity property on the overlay.
The procedure runs in four stages:
- Draw the image into an HTML
<canvas>so its pixel colors can be read. - Identify the pixel with the least contrast against the text.
- Build a color-mixing formula to simulate opacity levels over that pixel's color.
- Adjust opacity until contrast meets the goal, narrowing the range with binary search rather than random guessing.
Reading pixel colors with canvas
To read an image's colors, draw it onto a <canvas> element and call the context's getImageData() method to produce a list of the image's colors.
function getImagePixelColorsUsingCanvas(image, canvas) {
// The canvas's context (often abbreviated as ctx) is an object
// that contains a bunch of functions to control your canvas
const ctx = canvas.getContext('2d');
// The width can be anything, so I picked 500 because it's large
// enough to catch details but small enough to keep the
// calculations quick.
canvas.width = 500;
// Make sure the canvas matches proportions of our image
canvas.height = (image.height / image.width) * canvas.width;
// Grab the image and canvas measurements so we can use them in the next step
const sourceImageCoordinates = [0, 0, image.width, image.height];
const destinationCanvasCoordinates = [0, 0, canvas.width, canvas.height];
// Canvas's drawImage() works by mapping our image's measurements onto
// the canvas where we want to draw it
ctx.drawImage(
image,
...sourceImageCoordinates,
...destinationCanvasCoordinates
);
// Remember that getImageData only works for same-origin or
// cross-origin-enabled images.
// https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
const imagePixelColors = ctx.getImageData(...destinationCanvasCoordinates);
return imagePixelColors;
}
The returned data is a list of numbers, four per pixel: red, green, blue, and opacity (alpha). Looping over that list gives whatever per-pixel information is needed.

Finding the worst-contrast pixel
Contrast first has to be computed. A getContrast() function takes two colors and returns a number: the higher the value, the better the contrast for legibility. The calculation is not the single formula one might expect; it takes several steps.
Contrast depends on each color's luminance — essentially its brightness. The W3C gives the formula for deriving contrast from luminance, and getting luminance requires first converting the web's 8-bit RGB values (0–255) into linear RGB, because brightness does not rise evenly as colors change.
const contrast = (lighterColorLuminance + 0.05) / (darkerColorLuminance + 0.05);
const luminance = (0.2126 * getLinearRGB(r) + 0.7152 * getLinearRGB(g) + 0.0722 * getLinearRGB(b));
The conversion also passes through standard RGB (sRGB) on a 0-to-1 scale, so the chain is 8-bit RGB → sRGB → linear RGB. Once both colors' luminance is known, the two values go into the contrast formula.
8-bit RGB → standard RGB → linear RGB → luminance
// getContrast is the only function we need to interact with directly.
// The rest of the functions are intermediate helper steps.
function getContrast(color1, color2) {
const color1_luminance = getLuminance(color1);
const color2_luminance = getLuminance(color2);
const lighterColorLuminance = Math.max(color1_luminance, color2_luminance);
const darkerColorLuminance = Math.min(color1_luminance, color2_luminance);
const contrast = (lighterColorLuminance + 0.05) / (darkerColorLuminance + 0.05);
return contrast;
}
function getLuminance({r,g,b}) {
return (0.2126 * getLinearRGB(r) + 0.7152 * getLinearRGB(g) + 0.0722 * getLinearRGB(b));
}
function getLinearRGB(primaryColor_8bit) {
// First convert from 8-bit rbg (0-255) to standard RGB (0-1)
const primaryColor_sRGB = convert_8bit_RGB_to_standard_RGB(primaryColor_8bit);
// Then convert from sRGB to linear RGB so we can use it to calculate luminance
const primaryColor_RGB_linear = convert_standard_RGB_to_linear_RGB(primaryColor_sRGB);
return primaryColor_RGB_linear;
}
function convert_8bit_RGB_to_standard_RGB(primaryColor_8bit) {
return primaryColor_8bit / 255;
}
function convert_standard_RGB_to_linear_RGB(primaryColor_sRGB) {
const primaryColor_linear = primaryColor_sRGB < 0.03928 ?
primaryColor_sRGB/12.92 :
Math.pow((primaryColor_sRGB + 0.055) / 1.055, 2.4);
return primaryColor_linear;
}
With getContrast() in place, loop through every pixel and compare its color against the foreground text color, tracking the lowest contrast seen so far. When the loop ends, that tracked value is the worst-contrast color in the image.
function getWorstContrastColorInImage(textColor, imagePixelColors) {
let worstContrastColorInImage;
let worstContrast = Infinity; // This guarantees we won't start too low
for (let i = 0; i < imagePixelColors.data.length; i += 4) {
let pixelColor = {
r: imagePixelColors.data[i],
g: imagePixelColors.data[i + 1],
b: imagePixelColors.data[i + 2],
};
let contrast = getContrast(textColor, pixelColor);
if(contrast < worstContrast) {
worstContrast = contrast;
worstContrastColorInImage = pixelColor;
}
}
return worstContrastColorInImage;
}
Mixing colors for a given opacity
The next step is testing how different overlay opacities change the contrast with the text. An early implementation used a second canvas to mix colors and read the results; a formula instead computes the resulting color from a base color mixed with a transparent overlay. It is applied per red, green, and blue channel.
mixedColor = baseColor + (overlayColor - baseColor) * overlayOpacity
function mixColors(baseColor, overlayColor, overlayOpacity) {
const mixedColor = {
r: baseColor.r + (overlayColor.r - baseColor.r) * overlayOpacity,
g: baseColor.g + (overlayColor.g - baseColor.g) * overlayOpacity,
b: baseColor.b + (overlayColor.b - baseColor.b) * overlayOpacity,
}
return mixedColor;
}
With mixing in hand, the contrast can be tested for any given overlay opacity value.
function getTextContrastWithImagePlusOverlay({textColor, overlayColor, imagePixelColor, overlayOpacity}) {
const colorOfImagePixelPlusOverlay = mixColors(imagePixelColor, overlayColor, overlayOpacity);
const contrast = getContrast(textColor, colorOfImagePixelPlusOverlay);
return contrast;
}
Binary search for the optimal opacity
Finding the opacity where text ends up 4.5 times lighter than the background means probing many levels, but binary search converges quickly: guess the middle, eliminate the top half of the range if the guess is too high (the bottom half if too low), guess the middle of the new range, and repeat. Opacity spans 0 to 1; limiting the search to eight guesses yields a precise answer.
One check comes first: if no overlay is needed at all, there is nothing to optimize.
function isOverlayNecessary(textColor, worstContrastColorInImage, desiredContrast) {
const contrastWithoutOverlay = getContrast(textColor, worstContrastColorInImage);
return contrastWithoutOverlay < desiredContrast;
}
The search then runs within that check:
function findOptimalOverlayOpacity(textColor, overlayColor, worstContrastColorInImage, desiredContrast) {
// If the contrast is already fine, we don't need the overlay,
// so we can skip the rest.
const isOverlayNecessary = isOverlayNecessary(textColor, worstContrastColorInImage, desiredContrast);
if (!isOverlayNecessary) {
return 0;
}
const opacityGuessRange = {
lowerBound: 0,
midpoint: 0.5,
upperBound: 1,
};
let numberOfGuesses = 0;
const maxGuesses = 8;
// If there's no solution, the opacity guesses will approach 1,
// so we can hold onto this as an upper limit to check for the no-solution case.
const opacityLimit = 0.99;
// This loop repeatedly narrows down our guesses until we get a result
while (numberOfGuesses < maxGuesses) {
numberOfGuesses++;
const currentGuess = opacityGuessRange.midpoint;
const contrastOfGuess = getTextContrastWithImagePlusOverlay({
textColor,
overlayColor,
imagePixelColor: worstContrastColorInImage,
overlayOpacity: currentGuess,
});
const isGuessTooLow = contrastOfGuess < desiredContrast;
const isGuessTooHigh = contrastOfGuess > desiredContrast;
if (isGuessTooLow) {
opacityGuessRange.lowerBound = currentGuess;
}
else if (isGuessTooHigh) {
opacityGuessRange.upperBound = currentGuess;
}
const newMidpoint = ((opacityGuessRange.upperBound - opacityGuessRange.lowerBound) / 2) + opacityGuessRange.lowerBound;
opacityGuessRange.midpoint = newMidpoint;
}
const optimalOpacity = opacityGuessRange.midpoint;
const hasNoSolution = optimalOpacity > opacityLimit;
if (hasNoSolution) {
console.log('No solution'); // Handle the no-solution case however you'd like
return opacityLimit;
}
return optimalOpacity;
}
The result is the exact transparency that keeps the text readable while leaving the background image visible.
Limits and open edges
The method only works when the text color and overlay color already have sufficient contrast between them. Choose a text color identical to the overlay, and no optimal solution exists unless the image needs no overlay at all.
A mathematically acceptable contrast value does not guarantee good looks — particularly with dark text, a light overlay, and a busy image, where distracting regions can hurt readability even when the numbers pass. The popular recommendation is therefore light text on a dark background.
Pixel location and frequency are also ignored, so a single corner pixel could exert outsized influence on the result. The compensating benefit is that neither color distribution nor text placement needs handling: safe at the point of least contrast means safe everywhere else.
For the common case of white text on a black transparent overlay, one shortcut falls out: an opacity above 0.54 is never required to reach WCAG AA-level readability.



