How to remove certain elements before taking screenshot?

When I used this library I faced a problem that the lib download all the images in my application, that cause the application to run slowly. I resolved the problem using the ignoreElements option. This is my code:

  var DropAreaElement= document.getElementById("123");
    var config= {
        useCORS: true,
        ignoreElements: function (element) {
            if (element.contains(DropAreaElement) || element.parentElement.nodeName =="HTML" || element == DropAreaElement || element.parentNode == DropAreaElement) {
                console.log("elements that should be taken: ", element)
                return false;
            }else {
                return true;
            }
        }
    };
    html2canvas(DropAreaElement, config).then(function (canvas){
        var imgBase64 = canvas.toDataURL('image/jpeg', 0.1);
        console.log("imgBase64:", imgBase64);
        var imgURL = "data:image/" + imgBase64;
        var triggerDownload = $("<a>").attr("href", imgURL).attr("download", "layout_" + new Date().getTime() + ".jpeg").appendTo("body");
            triggerDownload[0].click();
            triggerDownload.remove();
    }).catch(Delegate.create(this, function (e){
        console.error("getLayoutImageBase64 Exception:", e);
    });

Add this attribute: data-html2canvas-ignore to any element you don't want to be taken when the screenshot is processed.

Hopefully this will help the next guy.


If you don't want to use an attribute, html2canvas does provide a method to remove elements. For example:

html2canvas( document.body, {
    ignoreElements: function( element ) {
        
        /* Remove element with id="MyElementIdHere" */
        if( 'MyElementIdHere' == element.id ) {
            return true;
        }
        
        /* Remove all elements with class="MyClassNameHere" */
        if( element.classList.contains( 'MyClassNameHere' ) ) {
            return true;
        }
        
    }
} ).then( function( canvas ) {
    document.body.appendChild( canvas );
} );

For more information, see html2canvas options.

Tags:

Html2Canvas