0

I am trying to compare different blocks of an image(filled.png) with a specific block of another image(blank.png). So far I have tried this :-

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = 20;
canvas.height = 20;
var img = new Image();
    img.onload = function(){
    context.drawImage(img,53,61,20,20,0,0,20,20);
};
img.src ='blank.png';
var imgResult = new Image();
var image1,image2;
var canvasResult = document.createElement('canvas');
canvasResult.width = 20;
canvasResult.height = 20;
var contextResult = canvasResult.getContext('2d');

function compare(){
    image1=new Image();
    image1.onload= function(){
         imgResult.onload = function(){
            var x = 53;
            for (var i = 1; i <= 20; i++) {
               contextResult.clearRect(0, 0, 20, 20);
               contextResult.drawImage(imgResult,x,61,20,20,0,0,20,20);
               x += 23;
               image2 = new Image();
               image2.onload = function(){
                   resemble(image1.src).compareTo(image2.src).onComplete(function(data){
                       $('p').append('Diffrence : ' + data.misMatchPercentage+ '%</br>');
                   });
               };
               image2.src = canvasResult.toDataURL();
           }
       };
     imgResult.src = 'filled.png';
   }
  image1.src=canvas.toDataURL();
}

But it is not working, getting same result on each iteration of for loop. So please help me find, where I am going wrong.

1 Answers1

0

.onComplete - sounds asynchronous, and image2.onload DEFINITELY IS - but in the meantime you're changing contextResult ... asynchronous code strikes again

If you create a function which recursively calls itself when each iteration completes, you should have better results:

e.g. with minimal code changes to what you have:

    imgResult.onload = function(){
        var x = 53, i = 1;
        var compare = function() {
            contextResult.clearRect(0, 0, 20, 20);
            contextResult.drawImage(imgResult,x,61,20,20,0,0,20,20);
            x += 23;
            image2 = new Image();
            image2.onload = function(){
                resemble(image1.src).compareTo(image2.src).onComplete(function (data) {
                    $('p').append('Diffrence : ' + data.misMatchPercentage+ '%</br>');
                    i += 1;
                    if (i <= 20) {
                        compare();
                    }
                });
            };
            image2.src = canvasResult.toDataURL();
        };
        compare();
    }
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87