简体   繁体   English

根据背景图像动态更改文本颜色

[英]Dynamically changing Text color depending on Background Image

right now I am writing a small chrome extension. 现在,我正在编写一个小的chrome扩展程序。 the extension grabs the Bing Image of the Day and sets it as the body background image, and then the extension also grabs the weather, time, date, etc. The problem is that sometimes the image of the day is for example, bright on one side and dark on the other. 该扩展程序获取当天的Bing图像并将其设置为人体背景图像,然后该扩展程序还获取天气,时间,日期等。问题是有时一天的图像有时会亮起来一边又黑暗。 So, no matter what color the text is, some of it is illegible. 因此,无论文本是什么颜色,其中一些都是难以辨认的。 How can I determine what color each text should be depending on the background image color behind a SPECIFIC text? 如何根据特定文本后面的背景图像颜色确定每个文本应为哪种颜色? Thanks in advance. 提前致谢。

You can use jQuery's attr() function. 您可以使用jQuery的attr()函数。 For example, if you img tag has an id attribute of 'my_image': 例如,如果您的img标签的id属性为“ my_image”:

<img id="my_image" src="first.jpg"/>

Jquery $("#my_image").attr("src","second.jpg"); jQuery $(“#my_image”)。attr(“ src”,“ second.jpg”);

I got something to work.... It is kind of makeshift and not foolproof, but I found a script that calculates overall brightness, which then allows the script to decide whether it should display black or white text. 我有一些工作要做。。。这是一种临时性的操作,但并非万无一失,但我找到了一个脚本来计算总体亮度,然后该脚本可以决定是显示黑色还是白色文本。 Seems to work well, as of now. 截至目前为止,似乎运作良好。 Here it is: 这里是:

function getImageBrightness(imageSrc) {
    var img = document.createElement("img");
    img.src = imageSrc;
    img.style.display = "none";
    document.body.appendChild(img);
    var colorSum = 0;
    img.onload = function () {
        // create canvas
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);
        var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        var data = imageData.data;
        var r, g, b, avg;

        for (var x = 0, len = data.length; x < len; x += 4) {
            r = data[x];
            g = data[x + 1];
            b = data[x + 2];

            avg = Math.floor((r + g + b) / 3);
            colorSum += avg;
        }

        brightness = Math.floor(colorSum / (this.width * this.height));
        console.log(brightness);
        if (brightness < 150) {
            $(".contrast").css("color", "white");
        } else {
            $(".contrast").css("color", "black");
        }
    }
}

credit to: https://jsfiddle.net/s7Wx2/ 归功于: https : //jsfiddle.net/s7Wx2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM