Skip to content

Instantly share code, notes, and snippets.

@McbeEringi
Last active September 17, 2021 12:51
Show Gist options
  • Save McbeEringi/e5fd7a87e53672166882ce3c786c5a60 to your computer and use it in GitHub Desktop.
Save McbeEringi/e5fd7a87e53672166882ce3c786c5a60 to your computer and use it in GitHub Desktop.
((e=document.documentElement,size=.5,c=document.createElement('canvas'))=>{
const ctx=c.getContext('2d'),
pre=x=>x.childNodes.forEach(y=>{
if(!y.tagName&&(y.textContent||'').trim()){
const el=document.createElement('span');
el.insertAdjacentHTML('beforeend',`<span>${y.textContent.replace(/</g,'>').replace(/([\n\r\s\t]+)/g,'</span>$1<span>')}</span>`.replace(/<span><\/span>/g,''));
y.parentNode.replaceChild(el,y);
}else pre(y);
}),
core=x=>{
const b=x.getBoundingClientRect(),s=window.getComputedStyle(x),
rect=[b.x,b.y,b.width,b.height].map(y=>Math.round(y*size));
if(rect.slice(2,4).every(y=>y)){
ctx.fillStyle=s.backgroundColor;ctx.fillRect(...rect);
if(!x.children.length){ctx.fillStyle=s.color;ctx.fillRect(...rect);}
if(['IMG','CANVAS'].includes(x.tagName)){x.crossOrigin='';ctx.drawImage(x,...rect);}
}
[...x.children].forEach(core);
},
b=e.getBoundingClientRect(),
cv=e.querySelectorAll('canvas');
e=e.cloneNode(true);document.body.appendChild(e);
e.style.cssText+=`position:fixed;top:0;left:0;visibility:hidden;width:${b.width}px;height:${b.height}px;`;
c.width=b.width*size;c.height=b.height*size;
pre(e);e.querySelectorAll('canvas').forEach((x,i)=>x.getContext('2d').drawImage(cv[i],0,0));
core(e);e.remove();
return c;
})(document.body).toBlob(b=>{
const a=document.createElement('a');
a.href=URL.createObjectURL(b);
a.textContent=`${location.href}.png`;
a.onclick=()=>setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},0);
a.style.cssText='position:fixed;top:50%;left:50%;z-index:99999;transform:translate(-50%,-50%);font-size:x-large;';
document.body.appendChild(a);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment