Elle Billias
Elle Billias

Reputation: 85

javascript to change font colour based on whether the image is more white or more black

Basically I have a website with a rotating background image and need to determine if the text on top of it should be white or black for the best contrast and readability.

Can this be done using javascript?

Upvotes: 3

Views: 683

Answers (2)

David Brainer
David Brainer

Reputation: 6331

If you did want to do this with JavaScript and you didn't mind that it would only work with browsers supporting canvas, here is a function that should do the trick:

function isBlack(cId, iId) {
    var blackThreshold = 127;

    var c = document.getElementById(cId);
    var i = document.getElementById(iId);

    c.width = i.width;
    c.height = i.height;

    var cxt = c.getContext('2d');
    cxt.clearRect(0,0, c.width-1, c.height-1);

    var img = new Image();
    img.src = i.src;
    cxt.drawImage(img,0,0);

    var imgd = cxt.getImageData(0, 0, c.width-1, c.height-1);
    var pix = imgd.data;

    var total = 0;
    for (var i = 0; n = pix.length, i < n; i += 4) {
      total += pix[i]+pix[i+1]+pix[i+2];
    }

    blackThreshold = (pix.length * .75) * blackThreshold;
    return (total < blackThreshold);
}

Note that this is quick and dirty and probably needs a lot of cleanup, but I tested it and it does do what you asked. For reference, here is the HTML I used when testing:

<canvas id="dummyCanvas" style="display: none;"></canvas>
<div>
    <img id="white" src="Hood_canal_2.jpg" />
    <h1 id="whiteText" style="margin-top: -200px; margin-bottom: 200px;">Text</h1>
</div>

<div>
    <img id="black" src="bw47.jpg" />
    <h1 id="blackText" style="margin-top: -200px; margin-bottom: 200px;">Text</h1>
</div>

Upvotes: 5

James Alday
James Alday

Reputation: 873

I don't think javascript would be well suited to this, at least on the client side.

ImageMagick has some tools for identifying the colors of an image and the number of pixels that match that color. If your images are pure black/white (two color) you could simply see which count is more, otherwise you'll have to have some kind of algorithm to figure out where your cutoff is (how dark of a gray you want to consider "black") and count them that way.

The IM method is getImageHistogram()

Upvotes: 3

Related Questions