tsayen / dom-to-image Goto Github PK
View Code? Open in Web Editor NEWGenerates an image from a DOM node using HTML5 canvas
License: Other
Generates an image from a DOM node using HTML5 canvas
License: Other
Error: SecurityError: DOM Exception 18
I seem to be getting this error only in Safari when I try to save a node. The node is a div with a fixed height and width, but with nothing in it.
OS X El Capitan 10.11.5 (15F34)
Safari Version 9.1.1 (11601.6.17)
firefox is rather having problem with too long data URL
Thanks so much for the awesome code! I'm building an Electron app - electron.atom.io - and need to create a series of png images of a specific div's contents, saving each frame of animation. I'm using the following script:
// domtoimg test
var stageContainer = document.getElementById('stage-container');
domtoimage.toPng(stageContainer)
.then(function (dataUrl) {
fs.writeFileSync('./tmp/pngs/img'+padded+'.png', dataUrl);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});
Files are saving but I am getting files that are unreadable as PNGs. They're coming out like this..
Is this something I'm doing or a bug?
with flex layout http://jsfiddle.net/tsayen/jk3vwebq/23/
without flex, still some strange artifacts appear http://jsfiddle.net/tsayen/jk3vwebq/24/
looks like the fonts should be base64 encoded and embedded
Hi,
Not an issue but a wish-feature.
Would be nice to be able to export SVGImageElement's as well as HTMLImageElement.
Been trying a workaround, but code gets me bit stuck. Will notify if we get to something.
Issue
Promise is Undefined
on Safari Browser (version [5.1.7)
Capturing vertical half image on Chrome Browser (version 49.0.2623.112)
var mainDiv = document.getElementById('mainDiv');
var canvas = document.createElement('canvas');
canvas.width = mainDiv.scrollWidth;
canvas.height = mainDiv.scrollHeight;
domtoimage.toPng(mainDiv).then(function (pngDataUrl) {
console.log(pngDataUrl);
}).catch(function (error) {
console.log("OOPS, something went wrong!.");
});
Perfect working on Mozila Browser
I did not get full image on chrome browser
Displaying White Space below portion
I use google api to fetch the font.
https://www.google.com/fonts#UsePlace:use/Collection:PT+Sans
And my dom is render using the same.
But the image render using dom-to-image
applies default browser font.
How do i fix this
In the README.md, there is one line document.appendChild(img);
. This will be an error in Chrome saying that "Failed to execute 'appendChild' on 'Node': Only one element on document allowed.".
Just tried to run test, as I want to contribute to this but there was a failture=(
Start:
domtoimage
✔ should load
INFO [Chrome 44.0.2403 (Mac OS X 10.10.4)]: Connected on socket LE5Fu9zSDlAM0HjSGFaS with id 31881270
✖ should render simple node
✖ should render big node
✖ should handle "#" in colors and attributes
✖ should render nested svg with broken namespace
✖ should render correctly when the node is bigger than container
✖ should render nested text nodes
✖ should render to blob
✖ should use node filter
Finished in 1 min 28.216 secs / 1 min 28.049 secs
SUMMARY:
✔ 2 tests completed
✖ 16 tests failed
FAILED TESTS:
domtoimage
✖ should render simple node
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
✖ should render big node
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 30000ms exceeded. Ensure the done() callback is being called in this test.
✖ should handle "#" in colors and attributes
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
✖ should render nested svg with broken namespace
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
✖ should render correctly when the node is bigger than container
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
✖ should render nested text nodes
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
✖ should render to blob
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
✖ should use node filter
Firefox 38.0.0 (Mac OS X 10.10.0)
Chrome 44.0.2403 (Mac OS X 10.10.4)
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
Warning: Task "karma:unit" failed. Use --force to continue.
I had really difficult times with node-canvas and cairo, did you install it without any problems?
Currently npm i node-canvas -g
return
> [email protected] install /usr/local/lib/node_modules/canvas
> node-gyp rebuild
SOLINK_MODULE(target) Release/canvas-postbuild.node
SOLINK_MODULE(target) Release/canvas-postbuild.node: Finished
CXX(target) Release/obj.target/canvas/src/Canvas.o
In file included from ../src/Canvas.cc:7:
../src/Canvas.h:22:10: fatal error: 'nan.h' file not found
I get a 'Promise' is undefined error on : dom-to-image.min.js, Line: 5, Column: 9
the line : return b = b || {}, Promise.resolve(a).then(function(a) {
When running on IE 11.0.9600.18204 on Windows 7 x64
asArray function throws error when arrayLike is null.
I've managed to patch it by simply adding check and returning empty array as a result.
Running the following example doesn't appear to render <rect>
in Chrome (Version 48.0.2564.116 (64-bit)):
http://jsfiddle.net/newtriks/cj82dupn/
I can confirm it does render fine in FireFox (Developer Version - 46.0a2 (2016-03-07)).
In firefox (41.0.2) getCssRules fails for stylesheets from external domains.
SecurityError: The operation is insecure.
util.asArray(sheet.cssRules || []).forEach(cssRules.push.bind(cssRules));
In particular it failed on such link:
<link href="//fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet">
Hello. I'm trying to use domtoimage in Mobile Safari.
The library is not loaded and no error is apparent. I added an alert at the beginning of the script and it does not show. If I remove all the content of the script the alert shows.
I will investigate the issue but I was wondering if the library had been tested on safari.
Hi,
May be its issue OR not
but i have some fonts added from google URL within my web page and when i do get dom to image it didn't render actual font faces which are getting render on web page from google URL.
please let me know if you can help.
Regards
Usman Abdul Razzaq
Hi
I've just started to use this library - very helpful.
Rendering dom with some remote image sources in it. Getting:
`XMLHttpRequest cannot load https://{bucket}.s3.amazonaws.com/uploads/North_face.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{me}' is therefore not allowed access.
I've checked the CORS settings on my bucket. All OK.
Curl from the same terminal, 200 OK.
Not quite sure where to go now. Where in the code do you set the request headers? Maybe that's where I'll start.
Thanks
Tom
when the namespace of it is set to sth other than the standard one for svg (seems like FF is OK with that)
looks like the same approach as with fonts should be taken
Trying to have screenshot of a youtube embed every 3 seconds but image is blank.
Got an svg that uses clilpPaths, but although they're properly rendered in browser, when exported to image, the overflowing region is not hidden.
http://jsfiddle.net/2tmeho0t/6/
Firefox - export KO
Chrome - export OK
Could this be a bug of dom-to-image or something you depend on? Any advise to fix it?
I got Event error when I run it on Safari 8.0.7
OOOOOOOPS, something went wrong!
Event
bubbles: false
cancelBubble: false
cancelable: false
clipboardData: undefined
currentTarget: null
defaultPrevented: false
eventPhase: 0
returnValue: true
srcElement: null
target: null
timeStamp: 1459283334222
type: "error"
__proto__: EventPrototype
the function I ran is like the following
function () {
domtoimage.toPng(document.querySelector('body'))
.then(function (dataUrl) {
var img = new Image();
img.src = dataUrl;
document.body.appendChild(img);
})
.catch(function (error) {
console.error('OOOOOOOOPS, something went wrong!', error);
});
}
Child element is larger than parent, but is not shown because parent has "overflow:hidden;" property.
Rendering parent element to image should produce an image the size of the parent, but is larger because of it's clipped children. The extra space is transparent for toPng(), and is black for toJpeg().
https://jsfiddle.net/yd6kkgqw/1/
Found in Chrome (Version 52.0.2743.82 m)
Verified in Firefox (Version 47.0.1)
If there are 'canvas' element under the node, the 'canvas' element is not saved(or saved with blank), should clone the canvas as a image and save it.
It would be extremely useful to be able to optionally specify the dimensions for the output image and have the image rendered at a higher resolution than the DOM element itself.
This would have numerous uses but would be particularly useful for printing the image afterwards. Printing at 72dpi (screen resolution) is not advisable!
One simple idea for making this happen is to scale the DOM element before rendering using the CSS *_zoom *_property or the CSS *_transform *_property. I attempted this but the bounding box for the element seems to remain the same, so while the elements do render larger, as expected, the image itself is cropped to the original size of the element, cutting out the bottom and right part of the element.
Absolute positioned elements do not display in Firefox, either as png or svg. They do in Chrome.
I've recreated the issue in this jsfiddle:
https://jsfiddle.net/andystanton/erdx3hs7/
I've specified right: 0
in the css but you don't have to supply any extra information other than absolute to reproduce.
OSX: 10.10.5
Chrome: 49.0.2623.112 (64-bit)
Firefox: 45.0.1
I and thx a lot for your job.
Do you will try to make a safari compatibility soon ?
Hiya,
Any chances of having some rendering options in order to add a watermark to the resulting image?
I got this message when I test on windows
From the message above, I have no clue which line gave that error message.
The function I ran was
function () {
domtoimage.toPng(document.querySelector('body'))
.then(function (dataUrl) {
var img = new Image();
img.src = dataUrl;
document.body.appendChild(img);
})
.catch(function (error) {
console.error('OOOOOOOOPS, something went wrong!', error);
});
}
Is there any error tracing method in your application?
I have this lines in my css
@font-face {
font-family: 'Glyphicons Halflings';
src: url(../fonts/glyphicons-halflings-regular.eot);
src: url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'), url(../fonts/glyphicons-halflings-regular.woff) format('woff'), url(.spd-editor-.spd-editor-/fonts/glyphicons-halflings-regular.ttf) format('truetype'), url(.spd-editor-.spd-editor-/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg');
}
but dom-to-image trying to get it by this url
http://localhost:9000/styles/.spd-editor-.spd-editor-/fonts/glyphicons-halflings-regular.ttf
Update: Appears to be a Chrome Bug, see comment.
In testing the library, I found the resultant image was larger than the dom element I was trying to capture.
There appears to be 3 extra pixels of height rendered below SVG elements. I've found the simplest case that illustrates: [https://jsfiddle.net/8kx0una9/]
A 100x100 pixel div, containing a 100x100 pixel SVG containing a 100x100 pixel path element.
Chrome inspector verifies all three elements rendered as 100x100 px (Version 52.0.2743.82 m)
Firefox (Version 47.0.1) produces a 100x100px image, as expected.
toPng() creates a png of the div at 100x103, with the extra 100x3 pixels as transparent.
toJpeg() creates a jpeg of the div at 100x103, with the extra 100x3 pixels as black.
Various Observations:
In the above fiddle, I could not get toPng() or toJpeg() to successfully render the SVG element directly (I don't know if that would be a separate bug, or a feature request).
Thanks for the work, btw... this looks almost perfect for my needs.
I have just downloaded the library.
I am hosting it on an apache server I have installed on my machine.
I am injecting the javascript to a given via the console
var url='https://guest.supporttip.com/static/tipcms/js/dom-to-image.min.js';var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=url;head.appendChild(script);
and then I try to run the code from the readme:
var node = document.body;
domtoimage.toPng(node)
.then(function (dataUrl) {
var img = new Image();
img.src = dataUrl;
document.body.appendChild(img);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});
I have tried this with several pages and it fails more often than not. Can someone assist?
if I try to pass an angular directive into toPng without having replace: true set, I get an error. See the plunker link below. If you uncomment the replace: true in the directive definition in app.js, it works fine.
The toolkit I'm using appends a jsessionid parameter to urls in order to distinguish the sessionid of the user. Which also means, when it generates an image, I end up with a dom element like this:
<img src="data/assets/image/121.jpg;jsessionid=8153D72A2FAA17F121E90D303763A947"/>
and when I try to take a screenshot of the area I'm interested into, it will always fail for the reason above,
even if I have access to that image from the browser (and indeed if I copy the url into a new tab, I can see the image), and the dom-to-image script is of course served from the same domain as the image (oh well, it's all running locally on my pc :-) ).
Hi, first of all, thanks for making this library public. You are a saint.
Testing on Chrome 49.0.2623.87 (64-bit) / Mac. My document has embedded fonts ( Google Fonts )
I'm having a problem when specifying filter function to .toSvg
- it fails when encounters a filtered out node.
var filterFunc = function( node ) {
if ( node.id == 'background' ) return true;
return false;
};
domtoimage.toSvg( container, { filter: filterFunc } )
.then( domtoimage.impl.util.makeImage )
.then( domtoimage.impl.util.delay( 100 ) )
.then( drawToCanvas )
.catch( function ( error ) { console.error( error ); } );
It fails / dies with the following error:
dom-to-image.js:198 Uncaught (in promise) TypeError: Cannot read property 'appendChild' of undefined
at dom-to-image.js:198:21
(anonymous function) @ dom-to-image.js:198
Promise.resolve (async)readAll @ dom-to-image.js:516
resolveAll @ dom-to-image.js:501
embedFonts @ dom-to-image.js:195
Promise.resolve (async)toSvg @ dom-to-image.js:32
On line 198 inside embedFonts
, node
is undefined. Because of all the Promises, I'm having a hard time actually debugging this. Do you have any ideas what could be causing this?
Hello ,
I am having lots of fonts in my app and while generating png image there are many ajax calls for getting these font files from the server. As i need to support many browsers hence there are font's in different formats and right now for a single image to be generated from DOM, the count for fetching fonts goes above 100.
Due to browser trying to fetch so many fonts, it freezes for a while when generating image. Is there any way by which i can reduce these downloads or supply those fonts in some way so that we need not tell browser to fetch it exclusively again as they are already fetched ?
This is dependent on document
how can this be updated to work in a server environment? Would it beable to handle a HTML String?
https://jsfiddle.net/sscm9nr7/
It generates the DOM element perfectly. CSS works just as it should. However, the text doesn't work. When I try this in Angular Material with <md-icon>add</md-icon>
for instance, the add
text gets included, but it has a default font (like Times New Roman).
With FontAwesome... Well, it's all squares.
Hi, I noticed that you only active contributor of domvas, and looks like this project the only solution for the transformation dom to the image, so this seems to me surprising that it have not got bigger support. Do you have some plans for this? As I see @pbakaus is no longer support this. Did you contact with him?
Hi there, first off, great library! This is helping find a solution to printing headers in Google Chrome that no one has seemed to be able to do easily and effectively.
The issue I have with the library is the height of a rendered textarea in SVG. If I have a textarea filled with text with a certain height set with an inline-style, looking at the SVG the textarea height is different. The heights I have been getting in the SVG are significantly taller than the true height of the textarea when passed into domtoimage.
I have got your excellent module working when I am printing an element found by its Id (as per your documentation) however I have a requirement to print HTML provided to me by an external service.
My attempt currently looks like this:
var fromHtml = function (html) {
var promise = $q(function(resolve, reject) {
var node = document.createElement('div');
node.innerHTML = html;
domtoimage.toPng(node)
.then(function (dataUrl) {
// Trim meta information
var trimmed = dataUrl.replace('data:image/png;base64,', '');
resolve(trimmed);
})
.catch(function (e) {
reject('Error converting HTML to canvas for printing: ' + e);
});
});
return promise;
};
The behaviour I am seeing is... nothing happens; it doesn't even hit my "catch".
I've had a look through the code and can't see anything obvious requiring the html passed into the .toPng(...) function be attached to the DOM however if I embed the HTML in my DOM and pass an Id as your docs it does work?
Have you got any ideas on this? I cannot easily embed the HTML into the DOM for every case.
Hello @tsayen ,
I am the member of cdnjs project.
We want to host this library.
But there are different naming in src
and dist
file in version 0.0.1
~0.0.5
.(domvas.js
)
What's your suggestion about changing the name from domvas
to dom-to-image
or keeping the same naming.
Thanks for your help!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.