I'm trying to make a download button and want the images to be downloadable. However, I'm facing trouble as two of my function toBlob
and save
functions are being told to be undefined
.
What am I doing wrong here? I'm using Vue.
methods: {
async downloadImage(val) {
const blob = await toBlob(src);
save(blob, 'image.jpg');
},
toBlob(src) {
new Promise((res) => {
const img = document.createElement("img");
const c = document.createElement("canvas");
const ctx = c.getContext("2d");
img.onload = ({ target }) => {
c.width = target.naturalWidth;
c.height = target.naturalHeight;
ctx.drawImage(target, 0, 0);
c.toBlob((b) => res(b), "image/jpeg", 0.5);
};
img.crossOrigin = "";
img.src = src;
});
save = (blob, name = "image.jpg") => {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.target = "_blank";
a.download = name;
a.click();
};
},
}