leiyanting

导航

 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
            html,body{
                height: 100%;
                overflow: hidden;
            }
            body{
                background: pink;
            }
            #test{
                background: gray;
                position: absolute;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                margin: auto;
            }
        </style>
    </head>
    <body>
        <canvas id="test" width="300" height="300">
            <span>您的浏览器不支持画布元素 请您换成萌萌的谷歌</span>
        </canvas>
    </body>
    <script type="text/javascript">
        window.onload=function(){
            var canvas = document.querySelector("#test");
            if(canvas.getContext){
                var ctx = canvas.getContext("2d");
                ctx.save();
                ctx.fillStyle="pink";
                ctx.beginPath();
                ctx.fillRect(50,50,100,100);
                ctx.restore();
                
                
                var imgdata = ctx.getImageData(0,0,canvas.width,canvas.height);
                /*var color = getPxInfo(imgdata,49,49);
                console.log(color);*/
                for(var i=0;i<imgdata.width;i++){
                    setPxInfo(imgdata,30,i,[0,0,0,255]);
                }
                
                ctx.putImageData(imgdata,0,0);
            }
            
            
            // 获取单像素信息函数
            function getPxInfo(imgdata,x,y){
                var color = [];
                
                var data = imgdata.data;
                var w = imgdata.width;
                var h = imgdata.height;
                
                //(x,y)  x*w+y
                //r
                color[0]=data[(y*w+x)*4];
                //g
                color[1]=data[(y*w+x)*4+1];
                //b
                color[2]=data[(y*w+x)*4+2];
                //a
                color[3]=data[(y*w+x)*4+3];
                
                return color;
            }
            
            // 设置单像素函数
            function setPxInfo(imgdata,x,y,color){
                
                var data = imgdata.data;
                var w = imgdata.width;
                var h = imgdata.height;
                
                //(x,y)  x*w+y   x:多少列  y:多少行
                //r
                data[(y*w+x)*4]=color[0];
                //g
                data[(y*w+x)*4+1]=color[1];
                //b
                data[(y*w+x)*4+2]=color[2];
                //a
                data[(y*w+x)*4+3]=color[3];
                
            }
        }
        
        
    </script>
</html>

 

posted on 2021-09-29 09:26  leiyanting  阅读(30)  评论(0编辑  收藏  举报