根据背景图像动态调整文本颜色 [英] Dynamically adjust text color based on background image

查看:111
本文介绍了根据背景图像动态调整文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一种产品,用于输出用户的图像,图像信息叠加在上述图像之上。正如您可能想象的那样,由于亮度/暗度,图像需要不同的文本颜色。有没有办法用JavaScript实现这个目标?

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 different text colors due to lightness/darkness. Is there a way to achieve this with JavaScript?

编辑:我发现了一个与我类似的问题,并且在jsfiddle中给出了一个解决方案( http://jsfiddle.net/xLF38/818 )。我虽然在我的网站上使用jQuery。如何将vanilla JavaScript转换为jQuery?

I found a similar question to mine and there was a solution given in a jsfiddle (http://jsfiddle.net/xLF38/818). I am using jQuery for my site though. How would I convert the vanilla JavaScript to jQuery?

var rgb = getAverageRGB(document.getElementById('i'));
document.body.style.backgroundColor = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';

function getAverageRGB(imgEl) {

    var blockSize = 5, // only visit every 5 pixels
        defaultRGB = {
            r: 0,
            g: 0,
            b: 0
        }, // for non-supporting envs
        canvas = document.createElement('canvas'),
        context = canvas.getContext && canvas.getContext('2d'),
        data, width, height,
        i = -4,
        length,
        rgb = {
            r: 0,
            g: 0,
            b: 0
        },
        count = 0;

    if (!context) {
        return defaultRGB;
    }

    height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
    width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;

    context.drawImage(imgEl, 0, 0);

    try {
        data = context.getImageData(0, 0, width, height);
    } catch (e) {
        /* security error, img on diff domain */
        alert('x');
        return defaultRGB;
    }

    length = data.data.length;

    while ((i += blockSize * 4) < length) {
        ++count;
        rgb.r += data.data[i];
        rgb.g += data.data[i + 1];
        rgb.b += data.data[i + 2];
    }

    // ~~ used to floor values
    rgb.r = ~~ (rgb.r / count);
    rgb.g = ~~ (rgb.g / count);
    rgb.b = ~~ (rgb.b / count);

    return rgb;

}


推荐答案

我终于发现了一些事情,正是我想做的事情!输入Brian Gonzalez的
jquery.adaptive-backgrounds.js 。看看这个:

I finally found something to do precisely what I want it to do! Enter Brian Gonzalez's jquery.adaptive-backgrounds.js. Check this out:

$parent.css({
        // backgroundColor: data.color
        color: data.color
});

我刚刚注释掉了backgroundColor规则并为颜色制作了一个新规则。对于白色文本,文本阴影如:

I just commented out the backgroundColor rule and made a new one for color. For white text, a text-shadow like:

text-shadow: 0 0 1px rgba($black, 0.3); // using Sass

应该足够了。感谢大家的回答!

should be enough. Thank you to everyone for your answers!

这篇关于根据背景图像动态调整文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆