I have found a way to save it as PDF but now I need to save it as Image.
This is my code:
function downloadCert()
{
html2canvas($('#canvas'), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL("image/jpeg");
console.log(imgData);
var pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);
pdf.save("download.pdf");
}
});
}
const downloadFile = () => {
const imgUri = 'data:image/gif;base64,R0lGODlhPQBEA....' //Image base64 uri
const link = document.createElement('a')
document.body.appendChild(link)
link.href = imgUri
link.target = '_self'
link.fileName = 'test_file_download.gif'
link.download = true
link.click()
}
The format in base64 string and the file extension should match for file to open properly. In above case, it's gif
Use this:
function blobCallback(fileName) {
return function(b) {
var a = document.createElement('a');
a.download = fileName+ '.jpeg';
a.href = window.URL.createObjectURL(b);
a.click();
}
}
$('#canvas').toBlob(blobCallback('DownloadFileName'), 'image/jpeg');
Related
I'm using the below code to download screenshots of my application:
download = filename => {
const a = document.createElement('a');
a.download = filename;
getDownloadURL().then(url => {
a.href = url;
document.body.appendChild(a);
a.click();
a.remove();
});
};
getDownloadURL = async () => {
const svg = document.querySelector('#widget svg'),
canvas = new OffscreenCanvas(svg.clientWidth * 3, svg.clientHeight * 3),
svgString = new XMLSerializer().serializeToString(svg),
ctx = canvas.getContext('2d'),
v = await Canvg.fromString(ctx, svgString, presets.offscreen());
await v.render();
const blob = await canvas.convertToBlob(),
pngUrl = URL.createObjectURL(blob);
return pngUrl;
},
The downloaded image has few unknown green lines at the background, what are these?
And how can these be removed?
This element appears fine in the application without these unknown lines.
I am trying to download a GIF from Giphy (just need to download it, I don't need to display it on the browser).
I tried using the solution in this question this question however it downloads a static image:
function download_img(e, link){
var image = new Image();
image.crossOrigin = "anonymous";
image.src = link;
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob;
// ... get as Data URI
if (image.src.indexOf(".jpg") > -1) {
blob = canvas.toDataURL("image/jpeg");
} else if (image.src.indexOf(".png") > -1) {
blob = canvas.toDataURL("image/png");
} else if (image.src.indexOf(".gif") > -1) {
blob = canvas.toDataURL("image/gif");
} else {
blob = canvas.toDataURL("image/png");
}
tempbtn = document.createElement('a');
tempbtn.href = blob;
tempbtn.download = 'giphy.gif'; // or define your own name.
tempbtn.click();
tempbtn.remove();
};
}
<a href="#" onclick="download_img(this,'https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif')" > Descargar gif </a>
I also wonder why it's needed to create a new Image(); and create a canvas tag
This works for me, I took some of the code from here
https://randomtutes.com/2019/08/02/download-blob-as-file-in-javascript/
(async () => {
//create new a element
let a = document.createElement('a');
// get image as blob
let response = await fetch('https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif');
let file = await response.blob();
// use download attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
a.download = 'myGif';
a.href = window.URL.createObjectURL(file);
//store download url in javascript https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access
a.dataset.downloadurl = ['application/octet-stream', a.download, a.href].join(':');
//click on element to start download
a.click();
})();
I managed to get this working in Chrome and Firefox too by appending a link to the to document.
var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
I am trying to write a function which will get the value from textarea and download it as an HTML file.
The HTML file
<textarea id="text-val" rows="4"></textarea>
Download your Code
The Javascript Function
function download(filename, html) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(html));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
var text = document.getElementById("text-val").value;
var filename = "MyCode.html";
download(filename, html);
}, false);
My question is : If a user put some external code source in textarea, as an example some image link. How can I download that image too and create a folder like images and put that image inside folder.
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
document.getElementById("dwn-btn").addEventListener("click", function(){
// Generate download of hello.txt file with some content
var text = document.getElementById("text-val").value;
var filename = "hello.html";
download(filename, text);
}, false);
<textarea id="text-val" rows="4"></textarea>
Download your Code
You can't download folders inside a browser. Although you might create a zip, either client side or server side, and download that zip
I know this code isn't optimized and a bit hacky but you can use it as a starting point.
It converts the image URL into base64 so it can be used inline with the downloaded HTML file.
document.getElementById("dwn-btn").addEventListener('click', function(event) {
event.preventDefault();
var content = document.getElementById("text-val").value;
content.match(/(src=".+"|src='.+')/g).forEach(function(match) {
var imageURL = match.substring(5).slice(0, -1);
var imageElem = document.createElement("img");
toDataURL(imageURL, function(dataUrl) {
var regex = new RegExp(imageURL);
content = content.replace(regex, dataUrl);
});
});
setTimeout(function(){
var blob = new Blob([content], {type: "text/html"});
var link = document.createElement("a");
link.download = "mydownloadedcode.html";
link.href = window.URL.createObjectURL(blob);
link.dispatchEvent(new MouseEvent("click"));
}, 2000);
});
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
<textarea id="text-val" rows="4">
<img id="imageid" src="https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0">
<img id="imageid" src='https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0'>
</textarea>
Download your Code
Try this URL, might be your issue solved
https://viralpatel.net/blogs/create-zip-file-javascript/
https://davidwalsh.name/javascript-zip
I want to download canvas as image but not working in firefox and microsoft edge but working with chrome
This is my code :
DownloadImage = (i) => {
var _this = this;
this.modeler.saveSVG(function (err, svg) {
if (err) console.log(err)
_this.setState({ datasvg: svg }, function () {
const canvas = _this.refs.canvasforimage;
const options = {
log: false,
ignoreMouse: true,
};
canvg(canvas, this.state.datasvg, options);
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const element = document.createElement("a");
element.setAttribute('download', 'diagram.png');
element.setAttribute('href', image);
element.click();
are there any solution ?
This is the code I use to save canvas contents as PNG image file:
canvas.toBlob(blob => {
var a = document.createElement("a"),
url = URL.createObjectURL(blob);
a.href = url;
a.download = "image.png";
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
});
Right now i am uploading image into canvas and after uploaded image, canvas converted into image by toDataURl. If i am converting canvas into image by toDataURL then i am getting base code(Base Code will be big). I want some small url instead of BaseCode.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
var img = document.createElement('img');
img.src = data;
img.onload = function () {
if (img.width < 300 || img.height < 300)
{
alert("upload image should be greater");
canvas.getActiveObject().remove();
}
};
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 50, top: 100,width:100, height:100, angle: 00}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
console.log("aaaaaaaaaaa" + dataURL);
// console.log("Canvas Image " + dataURL);
// document.getElementById('txt').href = dataURL;
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function (e) {
e.preventDefault();
canvas.deactivateAll().renderAll();
document.querySelector('#preview').src = canvas.toDataURL();
var b= canvas.toDataURL();
console.log(b);
}
canvas{
border: 1px solid black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="400" height="400"></canvas>
Click Me!!
<br />
<img id="preview" />
JSFiddle: https://jsfiddle.net/varunPes/8gt6d7op/23/
The devil is in the details - nowhere in the question do you even suggest you want to send the image somewhere - the code below is limited to the client - you can only use the short form url on the client, and as mentioned in a comment, only for a session (restart browser, url is useless), or until revokeObjectURL is called
You can - if the browser supports it, use a Blob, it's URL is short
// converts a dataURI to a Blob
function dataUriToBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var arrayBuffer = new ArrayBuffer(byteString.length);
var _ia = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteString.length; i++) {
_ia[i] = byteString.charCodeAt(i);
}
var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], { type: mimeString });
return blob;
}
// cross browser cruft
var get_URL = function () {
return window.URL || window.webkitURL || window;
};
// ... your code, which eventually does this
var b = canvas.toDataURL();
// get an URL from the Blob
var blob = dataUriToBlob(b);
var url = get_URL().createObjectURL(blob);
console.log(url);
//
// ... when finished with the object URL
URL.revokeObjectURL(url);
If you want to avoid send dataURL, you can convert it into DataForm using this function:
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
Then, call it:
var dataURL = canvas.toDataURL('image/jpeg', 0.5);
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);
Finally, send this form (regular or ajax).
Source answer