1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>马赛克</title> 6 <style> 7 body{background:#000;} 8 canvas{background: #fff; margin-left:500px;} 9 </style> 10 <script> 11 window.onload = function(){ 12 var cvs = document.getElementById(‘canvas1‘); 13 var cxt = cvs.getContext(‘2d‘); 14 15 var oImg = new Image(); 16 oImg.src = ‘1.jpg‘; 17 oImg.onload = function(){ 18 cxt.drawImage(this,0,0); 19 var imgData = cxt.getImageData(0,0,oImg.width,oImg.height); 20 var newImgData = cxt.createImageData(oImg.width,oImg.height); 21 var num = 10;//该参数指定马赛克格子的大小 22 23 var stepW = oImg.width/num;//一行内格子数 24 var stepH = oImg.height/num;//一列内格子数 25 26 27 for(var j=0;j<stepH;j++){ 28 for(var i=0;i<stepW;i++){ 29 //获取10*10方格内随机的一个颜色 30 var colors = getXY(imgData,i*num+Math.floor(Math.random()*num),j*num+Math.floor(Math.random()*num)); 31 //让10*10方格的颜色都为随机色 32 for(var s=0;s<num;s++){ 33 for(var t=0;t<num;t++){ 34 setXY(newImgData,i*num+t,j*num+s,colors); 35 } 36 } 37 38 } 39 } 40 41 cxt.putImageData(newImgData,0,oImg.height+50); 42 } 43 } 44 45 function getXY(imgData,x,y){ 46 var result = []; 47 result.push(imgData.data[(imgData.width*y+x)*4]); 48 result.push(imgData.data[(imgData.width*y+x)*4+1]); 49 result.push(imgData.data[(imgData.width*y+x)*4+2]); 50 result.push(imgData.data[(imgData.width*y+x)*4+3]); 51 return result; 52 } 53 54 function setXY(imgData,x,y,colors){ 55 imgData.data[(imgData.width*y+x)*4] = colors[0]; 56 imgData.data[(imgData.width*y+x)*4+1] = colors[1]; 57 imgData.data[(imgData.width*y+x)*4+2] = colors[2]; 58 imgData.data[(imgData.width*y+x)*4+3] = colors[3]; 59 } 60 61 62 </script> 63 64 </head> 65 <body> 66 <canvas id="canvas1" width="500" height="500"></canvas> 67 68 </body> 69 </html>
时间: 2024-12-09 21:06:46