I am trying to build an application in which I need to copy an entire div as an image to the clipboard. The div can contain nested divs and images, svgs etc.
I have searched for this a lot but am unable to find any answer to my requirement.
Currently, I can convert it to an image and open it in a new tab with the below code. However, it only works if there is plain text in the div. When I add an image, it fails. I just get a black screen copied.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/0.4.1/html2canvas.js"></script>
<script type="text/javascript">
function copy() {
var c = document.getElementsByClassName('myclass')[0];
html2canvas(c, {
onrendered: function(canvas) {
theCanvas = canvas;
var image = new Image();
image.id = "pic"
image.src = theCanvas.toDataURL();
image.height = c.clientHeight
image.width = c.clientWidth
window.open(image.src, 'Chart')
}
})
}
</script>
<button onclick='copy()'>Copy</button>
<div class="myclass">
Hi There!!!!!!!!
</div>
</body>
</html>
This helps me open the image in a new window. Any way to directly copy it to the clipboard rather than the right click context menu from the new window and make it all work with mixed content. Any help would be appreciated.
EDIT: I got the code to work with img
tag on hosting it on a local server and also made it work with svg
elements. But my app has mixed tags like the following:
<div>
<div>
some text here
<svg>
<g>...</g>
<g>...</g>
</svg>
<svg>
<g>...</g>
<g>...</g>
</svg>
<div>
some text here
</div>
</div>
</div>
Any ideas to make it work with all this so that I get the screenshot as it is. I also want it to work with IE, Chrome and Firefox. I tried using dom-to-image library but it does not support IE.
Thanks in advance
I have tested your code as following and it is working fine.
If you are html structure is something else can you paste its complete structure.