Dynamically adjust text color based on background image

前端 未结 3 1245

I am working on a product that outputs images from users and the image information is overlayed on top of the aforementioned images. As you might imagine, the images require

3条回答
  •  误落风尘
    2020-12-15 06:23

    This is possible using the canvas element. You would have to create a canvas element, draw the image element into the canvas, get the canvas's image data, look at the portion where the text is, convert those values to grayscale, average them, then compare them with a halfway point. Some example code:

    var img = document.getElementById('myImage');
    var c = document.createElement('canvas');
    var ctx = c.getContext('2d');
    var w = img.width, h = img.height;
    c.width = w; c.height = h;
    ctx.drawImage(img, 0, 0);
    var data = ctx.getImageData(0, 0, w, h).data;
    var brightness = 0;
    var sX = 0, sY = 0, eX = w, eY = h;
    var start = (w * sY + sX) * 4, end = (w * eY + eX) * 4;
    for (var i = start, n = end; i < n; i += 4) {
          var r = data[i],
              g = data[i + 1],
              b = data[i + 2];
          brightness += 0.34 * r + 0.5 * g + 0.16 * b;
          if (brightness !== 0) brightness /= 2;
    }
    if (brightness > 0.5) var textColor = "#FFFFFF";
    else var textColor = "#000000";
    

    I haven't tested this code, though it should work. Make sure to change the sX, sY, eX, eY values to only the area where your text is, otherwise you will get unsatisfactory results (it will still work). Good luck!

    EDIT: You will not have to display your image in any special way. Just make sure that the color of the overlay text is the variable textColor.

提交回复
热议问题