将图像的主要颜色设置为子div-jquery.fillcolor.js

时间:2018-10-16 20:36:52

标签: javascript jquery

我想在我的网站上使用jquery.fillcolor.js。
我想知道如何将图像主要颜色设置为子div,文本或按钮。

插件演示URL:https://codepen.io/farreal/pen/KRBZxG

<div class="parent js-fillcolor">
 <img src="some-image-url">
 <div class="child set-my-bg">I have a bg</div>
</div>

<script>
$(function () {
  $('.js-fillcolor').fillColor();
});
</script>

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

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;

}

答案 1 :(得分:0)

这可以通过使用 inherit 的 CSS 来完成:

.js-fillcolor .child {
    background-color: inherit;
}