js,canvas获取图片色值


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>获取图片的周边的色值</title>
</head>
<body>
<style type="text/css">
    canvas{
        /* position:absolute;
        opacity:0; */
    }
</style>
<!-- <div style="width:0;overflow:hidden"> -->
    <canvas id="canvas">对不你,你的浏览器不支持Canvas</canvas>
<!-- </div> -->
<div id="upside">up</div>
<div id="rightside">right</div>
<div id="downside">down</div>
<div id="leftside">left</div>
<script>
function getImgColor(url){
    function add(side,data,i){
        side[0]+=data[i];
        side[1]+=data[i+1];
        side[2]+=data[i+2];
        side[3]+=1;
    }
    function getColor(side){
        var r = side[0]/side[3];
        var g = side[1]/side[3];
        var b = side[2]/side[3];
        var color='rgb('+r+','+g+','+b+')';
        return color;
    }
    var img = new Image;
    img.src = url;
    img.onload = function(){
        canvas.setAttribute('width',img.width+'px');
        canvas.setAttribute('height',img.height+'px');
        var ctxt = canvas.getContext('2d');
        ctxt.drawImage(img, 0, 0);
        var data = ctxt.getImageData(0, 0, img.width, img.height).data;//读取整张图片的像素。
        var w=img.width;
        var h=img.height;
        var gap=3;
        var up=[0,0,0,0];
        var down=[0,0,0,0];
        var left=[0,0,0,0];
        var right=[0,0,0,0];
        
        for(var i =0,len = data.length; i<len;i+=4){
            if(i/4<w*gap){
                add(up,data,i)
            }else if(i/4%w<gap){
                add(left,data,i)
            }else if(i/4%w>w-gap){
                add(right,data,i)
            }else if(i/4>w*h-w*gap && i/4<w*h){
                add(down,data,i)
            }
        }
        var upcolor=getColor(up);
        var rightcolor=getColor(right);
        var leftcolor=getColor(left);
        var downcolor=getColor(down);
        upside.setAttribute('style',"background:"+upcolor);
        rightside.setAttribute('style',"background:"+rightcolor);
        leftside.setAttribute('style',"background:"+leftcolor);
        downside.setAttribute('style',"background:"+downcolor);
        console.log([upcolor,rightcolor,downcolor,leftcolor].toString());
    };
};
getImgColor('../img/banner/qq_01.jpg');//只需要把这个图片路径改成你自己的图片路径就行了
</script>

</body>
</html>

 

 

这是为了拿到图片四周各自的颜色,方便在设置背景色的时候使用,只是遍历所有像素可能效率比较低吧,不知道有什么更好的方法,计算的更快,更准

注意:直接在浏览器里打开会报错

Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

需要在服务器环境下打开!

posted @ 2018-08-30 12:06  cao_zhen  阅读(916)  评论(0编辑  收藏  举报