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);//新建ImgData对象 21 22 for(var j=0;j<oImg.height;j++){ 23 for(var i=0;i<oImg.width;i++){ 24 var res = getXY(imgData,i,j);//获取j行上某点的色彩 25 setXY(newImgData,i,oImg.height-j,res);//将该色彩设置给其倒影 26 } 27 } 28 29 cxt.putImageData(newImgData,0,oImg.height+50); 30 } 31 } 32 //获取(x,y)点的色彩信息 33 function getXY(imgData,x,y){ 34 var result = []; 35 result.push(imgData.data[(imgData.width*y+x)*4]); 36 result.push(imgData.data[(imgData.width*y+x)*4+1]); 37 result.push(imgData.data[(imgData.width*y+x)*4+2]); 38 result.push(imgData.data[(imgData.width*y+x)*4+3]); 39 return result; 40 } 41 //设置(x,y)点的色彩信息 42 function setXY(imgData,x,y,colors){ 43 imgData.data[(imgData.width*y+x)*4] = colors[0]; 44 imgData.data[(imgData.width*y+x)*4+1] = colors[1]; 45 imgData.data[(imgData.width*y+x)*4+2] = colors[2]; 46 imgData.data[(imgData.width*y+x)*4+3] = colors[3]; 47 } 48 49 50 </script> 51 52 </head> 53 <body> 54 <canvas id="canvas1" width="500" height="500"></canvas> 55 56 </body> 57 </html>
时间: 2024-12-27 05:06:42