Html2canvas: Feature - Ignore list for elements to be omitted from renderer

Created on 10 Jun 2014  路  6Comments  路  Source: niklasvh/html2canvas

A feature that can omit certain HTML elements from being rendered

for example
html2canvas(element, { ..., ignore: [".some-class", "#some-id"], ... });

will remove elements matching the ignore array but leave the DOM unaffected.

I have added this feature here

https://github.com/nchinan/html2canvas/commit/62c665c4acf20b1d8924da7bbb4c21335217c0ed

I would like to hear your feedback and suggestions

Regards
Neville

Feature

Most helpful comment

There is already an undocumented feature, that supports the required behavior. Whenever you add a data-html2canvas-ignore attribute to a DOM element, it is being ignored from rendering to the canvas.

All 6 comments

There is already an undocumented feature, that supports the required behavior. Whenever you add a data-html2canvas-ignore attribute to a DOM element, it is being ignored from rendering to the canvas.

The elements that I am trying to hide are generated by a another library at run-time. Unless I go into the library and modify the code to append data-html2canvas-ignore to the required elements this won't be possible.

@nchinan Can't you just modify your own code to search for and add the data attribute to the nodes, either before you take the screenshot or by using the onclone option? I don't see why you would need to modify the separate library. E.g.:

document.querySelectorAll('.some-class,#some-id').forEach( ... fn to add the data attribute ... );
html2canvas(element, options).then( ... your callback ... );

I'm noticing that with data-html2canvas-ignore, the element is hidden but not actually removed. The result being that there's an empty white space that's left behind where the element used to show. Is there a good way to actually remove that element form the canvas so that there isn't that ugly white space left behind?

See above comment--the way to do this would be to use the onclone option to modify the cloned document (e.g. set a class or style on the element that does display: none, or just remove said element) before rendering happens. The data-html2canvas-ignore doesn't do that by default as it would cause a reflow (expensive) and possibly also significantly change page rendering in unexpected ways.

Great, thanks. Still having some margin issues on the rendered image but this seems to work as intended. Example:

html2canvas($("body"), {
onclone: function(document) {
if (options.elementsToIgnore.length) {
for (var i = 0; i < options.elementsToIgnore.length; i++) {
$(document).find(options.elementsToIgnore[i]).remove();
}
}
}}).then(function(canvas) {
var imgData = canvas.toDataURL('image/png');
var doc = new jsPDF('p', 'pt', 'a4');
doc.addImage(imgData, 'PNG', 0, 0);
doc.save('sample-file.pdf'); //creates a pdf
}).catch(function(error) {
done(error);
});

Was this page helpful?
0 / 5 - 0 ratings