Search code examples
htmlcanvastodataurl

Canvas & Resemble.js: toDataURL() Not Working


I have an html5 video that I am taking screenshots from using:

context.drawImage(video, 0, 0, w, h);

This draws the screenshot on the canvas just fine. However, what I am trying to do is take multiple screenshots on multiple canvas and compare them with each other using Resemble.js.

Resemble.js requires two files, and I am trying to use toDataURL() to get these files from the canvases.

var image1 = new Image();
        image1.id = "pic"
        image1.src = canvas1.toDataURL("image/png");

And then plugging the images into resemble:

resemble(image1).compareTo(image2).onComplete(function(){
            //return data;
            alert(data);
        /*
        {
          misMatchPercentage : 100, // %
          isSameDimensions: true, // or false
          getImageDataUrl: function(){}
        }
        */
            });

Where this seems to fail for me is toDataURL(). It does not produce anything from the canvas. What is causing this issue? And am I on the right track with my approach?


Solution

  • Give both images time to load:

    var loadCount;
    var image1,image2;
    
    function compare(){
    
        // variable to count how many images have fully loaded
    
        loadCount=0;
    
        // convert canvas1 to an image
        // call startComparing when done
    
        image1=new Image();
        image1.onload=startComparing;
        image1.src=canvas1.toDataURL();
    
        // convert canvas2 to an image
        // call startComparing when done
    
        image2=new Image();
        image2.onload=startComparing;
        image2.src=canvas2.toDataURL();
    
    }
    
    
    function startComparing(image1,image2){
    
        // do the comparison only if we've loaded both images (loadCount==2)
    
        if(++loadCount==2);
    
            resemble(image1).compareTo(image2).onComplete(function(data){
                alert(data);
            });
    
        }
    
    }