HTML5自学笔记[ 21 ]canvas绘图实例之马赛克

时间:2021-09-13 13:37:37
 <!DOCTYPE html>
 <html>
 <head lang="en">
     <meta charset="UTF-8">
     <title>马赛克</title>
     <style>
         body{background:#000;}
         canvas{background: #fff; margin-left:500px;}
     </style>
     <script>
         window.onload = function(){
             var cvs = document.getElementById('canvas1');
             var cxt = cvs.getContext('2d');

             var oImg = new Image();
             oImg.src = '1.jpg';
             oImg.onload = function(){
                 cxt.drawImage(this,0,0);
                 var imgData = cxt.getImageData(0,0,oImg.width,oImg.height);
                 var newImgData = cxt.createImageData(oImg.width,oImg.height);
                 var num = 10;//该参数指定马赛克格子的大小

                 var stepW = oImg.width/num;//一行内格子数
                 var stepH = oImg.height/num;//一列内格子数

                 for(var j=0;j<stepH;j++){
                     for(var i=0;i<stepW;i++){
                         //获取10*10方格内随机的一个颜色
                         var colors = getXY(imgData,i*num+Math.floor(Math.random()*num),j*num+Math.floor(Math.random()*num));
                         //让10*10方格的颜色都为随机色
                         for(var s=0;s<num;s++){
                             for(var t=0;t<num;t++){
                                 setXY(newImgData,i*num+t,j*num+s,colors);
                             }
                         }

                     }
                 }

                 cxt.putImageData(newImgData,0,oImg.height+50);
             }
         }

         function getXY(imgData,x,y){
             var result = [];
             result.push(imgData.data[(imgData.width*y+x)*4]);
             result.push(imgData.data[(imgData.width*y+x)*4+1]);
             result.push(imgData.data[(imgData.width*y+x)*4+2]);
             result.push(imgData.data[(imgData.width*y+x)*4+3]);
             return result;
         }

         function setXY(imgData,x,y,colors){
             imgData.data[(imgData.width*y+x)*4] = colors[0];
             imgData.data[(imgData.width*y+x)*4+1] = colors[1];
             imgData.data[(imgData.width*y+x)*4+2] = colors[2];
             imgData.data[(imgData.width*y+x)*4+3] = colors[3];
         }

     </script>

 </head>
 <body>
 <canvas id="canvas1" width="500" height="500"></canvas>

 </body>
 </html>