使用resemble.js

时间:2016-09-28 11:00:20

标签: javascript resemblejs

我试图将图像的不同块(filled.png)与另一个图像的特定块(blank.png)进行比较。 到目前为止,我已经尝试过这个: -

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();
}

但它不起作用,在for循环的每次迭代中得到相同的结果。所以请帮助我找到我错的地方。

1 个答案:

答案 0 :(得分:0)

image2.onload - 听起来是异步的, 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(); } 肯定是 - 但与此同时你改变了contextResult ...异步代码再次出现

如果你创建一个在每次迭代完成时递归调用自身的函数,你应该有更好的结果:

e.g。使用最少的代码更改您拥有的内容:

NSMutableArray *arrSelected = [[NSMutableArray alloc] init];

NSArray *arrProductSelection = [[NSArray alloc]initWithObjects:@"English",@"German",@"Russian",@"Chinese",@"Spanish",@"French",@"French",@"French",@"French",@"French",@"French",@"French",@"French",nil];

NSArray *arrProductSelectionB = [[NSArray alloc]initWithObjects:@"deselcted",@"selected",@"selected",@"selected",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",nil];

for(int i = 0; i< arrProductSelectionB.count-1;i ++) {
    if ([arrProductSelectionB[i] isEqualToString:@"selected"]) {
        [arrSelected addObject:arrProductSelection[i]];
    }
}

NSString *strSelected = [arrSelected componentsJoinedByString:@","];

NSLog(@"%@", strSelected);//output: German,Russian,Chinese