I tried the dom-to-image library to download a set of HTML div. The “to-image” part worked just fine, but after the div
was converted to an image, I want it also downloaded directly as an image. But I can’t do that.
The dom-to-image docs said you can create an anchor element, and put the attributes there, and activate with the click()
function:
let link = document.createElement('a');
link.download = 'my-image-name.png';
link.href = dataUrl;
link.click();
here is the example I made with svelte, it won’t download, if I put the anchor as a child, I can’t click the link. BUT, I can right-click and open in new tab
or open image in new tab
and also save image as
. So I think there’s no problem with the src/URL.
<script>
import domtoimage from 'dom-to-image'
let capture, display = false
function close() {
display = !display
document.querySelector(".image").remove()
}
function save() {
console.log("save")
display = !display
domtoimage.toPng(capture)
.then(function (dataUrl) {
let link = document.createElement('a');
link.download = 'my-image-name.jpeg';
link.href = dataUrl;
link.click(); //not working
let img = new Image();
img.src = dataUrl;
img.className = "image"
let show = document.querySelector(".show")
show.appendChild(link).appendChild(img);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
//no error logged
});
}
</script>
<div class="capture" bind:this={capture}>
<h1 >Hello World!</h1>
<p>
<!-- long text just for example -->
</p>
</div>
<button on:click={save}>
save
</button>
<div class="show" class:display={display}>
<button on:click={close}>
close
</button>
</div>
<style>
.capture {
background-color:cornflowerblue;
padding:1rem;
color:white
}
h1 {
background-color:lavender;
padding:1rem;
color:coral
}
.show {
position:absolute;
top:0;
width:100vw;
height:100vh;
background-color:rgba(0,0,0,0.5);
display:none;
}
.display {
display:block;
}
</style>
UPDATE
I recreate the code in codepen and it works, so it’s a svelte problem? or just the svelte REPL environment problem? I need to implement in my own svelte environment later.