Trying to compare two Canvas elements

前端 未结 2 1899
感动是毒
感动是毒 2021-01-04 16:51

I am using below code to compare two canvas elements

function createImage(html, can) {
     var canvas = $( \"#\" + can );
     var ctx = canvas[0].getCont         


        
2条回答
  •  花落未央
    2021-01-04 17:48

    The reason you get a cross-origin error is because of the use of with namespace declarations located at http://www.w3.org/, which is of a different origin:

    var data = "" +
                 "" +
                   "
    " + html + "
    " + "
    " + "
    ";

    I can tell this method is the one from Drawing DOM objects into a canvas on MDN.

    When you re-access the data this way,

    var ctx1 = a1.getContext('2d');
    var imageData = ctx1.getImageData(0, 0, a1.width, a1.height);
    

    you will hit the error:

    Unable to get image data from canvas because the canvas has been tainted by cross-origin data.

    You can test this on Chrome:

    • Your original version with the error
    • Another version with namespace declarations removed, which does not throw an error and is at the same time blank due to the absence of namespace declarations

    You can only return the data from the function to avoid getting this error. But because of the asynchronous nature of img.onload,

    img.onload = function () {
        ctx.drawImage(img, 0, 0);
        DOMURL.revokeObjectURL(url);
    };
    

    you have to defer the retrieval of data, forcing you to re-access the data out of the function and causing the error.

    Thus, you should use an alternate method of building the canvas with DOM objects that does not rely on , like html2canvas.

    function createImage(html) {
        var dfd = new $.Deferred();
        var el = document.createElement("div");
            el.innerHTML = html;
            el.style.display = 'inline-block';
            document.body.appendChild(el);
        html2canvas(el, {
          onrendered: function(canvas) {
              document.body.appendChild(canvas);
              document.body.removeChild(el);
              dfd.resolve(canvas.toDataURL());
          }
        });
        return dfd;
    }
    $.when(
        createImage("Hello"), 
        createImage("Hello")
    ).done(function(a1, a2){
       if (a1 === a2) {
          alert("Match"); 
       }
    });
    

    See DEMO.

提交回复
热议问题