通过拍摄图像平均颜色设置字体颜色 [英] setting font color by taking image average color

查看:174
本文介绍了通过拍摄图像平均颜色设置字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的HTML5项目,我需要通过取出背景图像的平均值来设置字体颜色。例如,这是我的背景有两个文本框textbox1和textbox2。

I have an interesting HTML5 project where i need to set the font color by taking out the average of background image. For example this is my background which has two textboxes textbox1 and textbox2.

图像

为了得到textbox1的颜色,我需要计算背景图像部分的平均值,然后设置颜色。类似地,对于textbox2我需要计算其背景图像的平均值,然后设置颜色。我可以获得文本框位置,但如何计算平均颜色?我很困惑。任何建议如何可以使用jquery或css?

In order to get the color of textbox1 i need to calculate the average of the background image portion and then set the color. Similarly for textbox2 i need to calculate the average of its background image and then set the color .I can get the textbox positions but how can i calculate the average colors?I am very confused. Any recommendations of how can it be done using jquery or css?? .

推荐答案

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;

}

用法:

var rgb = getAverageRGB(document.getElementById('image'));

示例:

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

资料来源:通过javascript 获得图像的平均颜色

Source: get average color of image via javascript

这篇关于通过拍摄图像平均颜色设置字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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