JSFiddle - React, Tailwind, and code Playground
by walid154
HTML
<!--example-->
<link href="https://fonts.googleapis.com/css?family=Quicksand:300,500" rel="stylesheet">
<section><p>Dolor sit amet consectetur <a href="#">adipiscing elit</a> curabitur vel hendrerit.</p></section>
<p><button>to img</button></p>
CSS
html, body {
margin: 0;
padding: 0;
height: 100%;
}
body {
padding: 1rem;
height: 12rem;
}
* {
font-family: 'Quicksand', sans-serif;
font-weight: 300;
}
p:first-letter {
font-weight: bold;
font-size: 3rem;
}
a {
color: blue;
text-decoration: underline;
}
img {
box-shadow: 0 0 1rem #ddd;
}
JavaScript
const {body} = document
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const tempImg = document.createElement('img')
tempImg.addEventListener('load', onTempImageLoad)
const targetImg = document.createElement('img')
body.appendChild(targetImg)
body.querySelector('button').addEventListener('click', onButtonClick)
function onButtonClick(){
const style = `<style>${document.querySelector('style').innerHTML}</style>`
const element = body.querySelector('section')
const {outerHTML, offsetWidth, offsetHeight} = element
const html = outerHTML.replace(/\n/g,'')
//
const svgString = getSVGString(offsetWidth,offsetHeight,style,html)
//
tempImg.src = 'data:image/svg+xml,' + encodeURIComponent(svgString)
canvas.width = offsetWidth
canvas.height = offsetHeight
}
function onTempImageLoad(e){
console.log('onTempImageLoad...',tempImg)
ctx.drawImage(e.target, 0, 0)
targetImg.src = canvas.toDataURL()
}
function getSVGString(w,h,style,html) {
return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">${style}<foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">${html}</div></foreignObject></svg>`
}