Skip to content

Instantly share code, notes, and snippets.

@yetone
Created March 15, 2017 10:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetone/bcb05f618d9e06492ebde79c9e102007 to your computer and use it in GitHub Desktop.
Save yetone/bcb05f618d9e06492ebde79c9e102007 to your computer and use it in GitHub Desktop.
const noop = () => {}
const supportsCSSText = getComputedStyle(document.body).cssText !== ''
function copyCSS(elem, origElem) {
let computedStyle = getComputedStyle(origElem)
if (supportsCSSText) {
elem.style.cssText = computedStyle.cssText
} else {
Object.keys(computedStyle).forEach(prop => {
if (isNaN(parseInt(prop)) && typeof computedStyle[prop] !== 'function' && !(/^(cssText|length|parentRule)$/).test(prop)) {
elem.style[prop] = computedStyle[prop]
}
});
}
}
function inlineStyles(elem, origElem) {
let children = elem.querySelectorAll('*')
let origChildren = origElem.querySelectorAll('*')
copyCSS(elem, origElem)
Array.prototype.forEach.call(children, function(child, i) {
copyCSS(child, origChildren[i])
})
elem.style.margin = elem.style.marginLeft = elem.style.marginTop = elem.style.marginBottom = elem.style.marginRight = ''
}
const dom2img = {
toImage({ elem, callback = noop, processElem = noop, width, height, left = 0, top = 0 }) {
const _elem = elem.cloneNode(true)
inlineStyles(_elem, elem)
processElem(_elem)
_elem.setAttribute("xmlns", "http://www.w3.org/1999/xhtml")
const serialized = new XMLSerializer().serializeToString(_elem)
const url = `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="${ (width || elem.offsetWidth) + left }" height="${ (height || elem.offsetHeight) + top }">
<foreignObject width="100%" height="100%" x="${ left }" y="${ top }">
${ serialized }
</foreignObject>
</svg>`
const img = new Image()
img.onload = function() {
callback.call(this, this)
}
img.src = url
}
};
export default dom2img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment