计算图片主题颜色,附件是例子图片和执行效果图。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>图片主题色</title> <script src="../../lib/jquery.js"></script> <script> function calcThemeColor(image){ var context=document.createElement('canvas').getContext("2d"); context.drawImage(image,0,0); var imageData=context.getImageData(0,0,image.width,image.height); var worker=new Worker("calcColor.js"); worker.postMessage(imageData); worker.onmessage=function(event){ var themeColor=event.data; $("body").css("background","rgb("+themeColor.red+","+themeColor.green+","+themeColor.blue+")"); console.log(themeColor); }; } </script> </head> <body> <img id="image" onload="calcThemeColor(this)" src="images/1.jpg" alt="" /> </body> </html>
onmessage=function(event){ var imageData=event.data; var rSum=0; var gSum=0; var bSum=0; var dataCount=imageData.data.length/4; for(var i=0,n=imageData.data.length;i<n;i+=4){ var num=i/4; var redColor=imageData.data[i+0]; var greenColor=imageData.data[i+1]; var blueColor=imageData.data[i+2]; var avgR=num>0?rSum/num:redColor; if(Math.abs(redColor-avgR)<250){ rSum+=avgR; }else{ rSum+=redColor; //red } var avgG=num>0?gSum/num:greenColor; if(Math.abs(greenColor-avgG)<250){ gSum+=avgG; }else{ gSum+=greenColor; //green } var avgB=num>0?bSum/num:blueColor; if(Math.abs(blueColor-avgB)<250){ bSum+=avgB; }else{ bSum+=blueColor; //blue } //var a=imageData.data[i+3]; //alpha } var themeColor={ red:Math.round(rSum/dataCount), green:Math.round(gSum/dataCount), blue:Math.round(bSum/dataCount) }; postMessage(themeColor); }