检测图像是暗/亮还是将父级(暗/亮)添加到父级

时间:2016-07-05 20:03:51

标签: javascript jquery html

在这个小提琴上,这些功能完美地完成了这项工作,但我需要稍微调整一下这个结点。

  • 点击甚至需要是父div的addClass(dark / light)(true为false)。
  • 如果黑暗addClass Bright。
  • 如果光图像addClass黑暗。

有没有办法让这个功能做我需要的?

getImageBrightness(this.src,function(brightness) {
            document.getElementsByTagName('pre')[0].innerHTML = "Brightness: "+brightness;
        });

jsfiddle.net/s7Wx2 /

1 个答案:

答案 0 :(得分:1)

Working Fiddle Here.

在您的HTML中,我只在id添加了img 我玩了一点纯粹的javascript getImageBrightness ......但不是那么多。

我使用" 127.5"作为黑暗与光明之间的中间线 我建议你评价一下......因为人眼不像脚本一样数学 ;)


这是脚本:

var thisImg;

function getImageBrightness(image,callback) {
    var thisImgID = image.attr("id");

    var img = document.createElement("img");
    img.src = image.attr("src");

    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;
        }

        var brightness = Math.floor(colorSum / (this.width*this.height));
        callback(thisImgID, brightness);
    }
}

$("img").on("click", function(){
    thisImg = $(this)

    getImageBrightness( $(this),function( thisImgID, brightness ) {     
        document.getElementsByTagName('pre')[0].innerHTML = "Brightness: "+brightness+"<br><br>- Red border means class added -> dark,<br>- yellow border mean class added -> light";

        if(brightness<127.5){
            $("#"+thisImgID).addClass("dark");
        }else{
            $("#"+thisImgID).addClass("light");
        }
    });
});

CSS:

.dark{
    border:3px solid red;
}
.light{
    border:3px solid yellow;
}