用canvas做图片对比
以前和别人联机玩连连看的时候,总是一群人围在一起看;不过就算是一群人看一个人也总有看不到的时候。
那时候就想要是有 个外挂就好了。
HTML5的Canvas是可以处理像素级的信息的。那可否用Canvas来比较呢。自己PS两个图来测试一把。
A.PNG
B.PNG
写完代码,LOAD到页面中。DIFF出来信息。
1 <style> 2 .canvas{ width:500px; height:300px; background-color: #DDD;margin: 20px auto;} 3 </style> 4 <body> 5 <div class="canvas"> 6 <canvas id="canvas" width ="500" height="300" > </canvas> 7 </div> 8 9 <script type="text/javascript"> 10 11 var canvas = document.getElementById('canvas'), 12 ctx = canvas && canvas.getContext && canvas.getContext('2d'), 13 imageData, pixelArray; 14 var imgA,imgB,callBack; 15 16 imgA = new Image(); 17 imgA.onload = function() { 18 ctx.drawImage(this, 50,100); 19 imgA = ctx.getImageData(50, 100, this.width, this.height); 20 imgB = new Image(); 21 imgB.onload = function() { 22 ctx.drawImage(this, 200,100); 23 imgA = ctx.getImageData(200, 100, this.width, this.height); 24 callBack(); 25 }; 26 imgB.src = 'B.png'; 27 }; 28 imgA.src = 'A.png'; 29 callBack = function(){ 30 31 imageData = ctx.getImageData(50, 100, 100,100); 32 pixelArray = imageData.data; 33 34 compImage = ctx.getImageData(200, 100, 100,100); 35 compData = compImage.data;; 36 37 for (var i=0, len=pixelArray.length; i<len; i+=4) { 38 var r = pixelArray[i], 39 g = pixelArray[i+1], 40 b = pixelArray[i+2], 41 a = pixelArray[i+3]; 42 43 var r1 = compData[i], 44 g1 = compData[i+1], 45 b1 = compData[i+2], 46 a1 = compData[i+3]; 47 48 var a = [r,g,b,a].join('-'); 49 var b = [r1,g1,b1,a1].join('-'); 50 if( a !== b ){ 51 pixelArray[i] = 255 - r; 52 pixelArray[i+1] = 255 - g; 53 pixelArray[i+2] = 255 - b; 54 }else{ 55 pixelArray[i] = 0; 56 pixelArray[i+1] = 0; 57 pixelArray[i+2] = 0; 58 } 59 60 61 } 62 ctx.putImageData(imageData, 350, 100); 63 } 64 </script> 65 66 </body>