Canvas.toDataURL() returns a file without extension - javascript

I'm converting an HTML canvas into a jpg when a save button is clicked. I use the code below:
$('#save').click(function(e){
var canvas = $('#myCanvas')[0];
var image = canvas.toDataURL("image/png").replace("image/png","image/octet-stream");
window.location.href=image; // it will save locally
});
Unfortunately, I download file without any extension. What I want is when I click the download button, The browser must download file from the page with a file extension.
Thanks

#K3N's answer didn't work for me because as mentioned:
Ideally you set the href before the click somehow.
I built on top of it and did this and it works great.
var btnSave = document.getElementById('btnSave');
btnSave.addEventListener('click', function() {
var image = photo.toDataURL("image/png");
var anchor = document.createElement('a');
anchor.setAttribute('download', 'myFilename.png');
anchor.setAttribute('href', image);
anchor.click();
});

Assuming your #save element is an anchor tag (<a ...></a>) you can do this:
$('#save').click(function(e){
var canvas = $('#myCanvas')[0];
var image = canvas.toDataURL("image/png");
$('#save').attr({
'download': 'myFilename.png', /// set filename
'href' : image /// set data-uri
});
});
Ideally you set the href before the click somehow.

You should use:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
for loading,you need to use:
document.write('<img src="'+img+'"/>');

Related

Download canvas.todataurl via window.location (How to change filename?)

I create a jpeg file over canvas. The image is downloaded and has the name "Download" without file extension. How can I modify the file name for the download via the script?
html2canvas(document.getElementById("rankingTable")).then(function (canvas) {
var image = canvas.toDataURL("image/png", 1)
.replace("image/png", "image/octet-stream");
window.location.href=image;
});
Specify the filename in the download attribute:
function downloadData(linkData, filename) {
let link = document.createElement('a');
link.href = linkData;
link.download = filename;
let target = document.body;
target.appendChild(link); // Firefox requires the link to be in the body
link.click(); // simulate click
target.removeChild(link); // remove the link when done
}
Doc: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download
I am not sure you need to replace the "image/png" with "image/octet-stream", so try this code:
html2canvas(document.getElementById("rankingTable")).then(function (canvas) {
var image = canvas.toDataURL("image/png", 1);
downloadData(image, "ranking-table.png");
});

chart js download to png with canvas.toDataURL() not working in IE and firefox

I am using canvas.toDataURL() to download chart.js chart ,it is perfectly working with chrome but not working with IE and Firefox.here is my code
var link = document.createElement('a');
var canvas = document.getElementById('canvasId');
link.href = canvas.toDataURL("image/png");
link.download = 'IMAGE.png';
link.click();
Thank you.
var canvas = document.getElementById('canvasId');
if(canvas.msToBlob){
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, 'image.png');
}
else{
var link = document.createElement('a');
link.href = canvas.toDataURL("image/png");
link.download = 'IMAGE.png';
document.body.append(link);
link.click();
}
The anchor tag you are creating also needs to be added to the DOM in Firefox and IE, in order to be recognized for click events.
In Firefox, you need to do the link.click (though you may not want to do that in Chrome as it results in a double download). However, IE (except for the latest versions of Edge) doesn't support the "download" attribute on the a tag, and you need to save the canvas slightly differently.
var canvas = document.getElementById('canvasId');
var isIE = !!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g);
if (!isIE) {
let image = canvas.toDataURL("image/jpeg", 1.0);
// we are getting the a tag to add the 'download' attribute and the file contents
let downloadLink = document.getElementById("download");
downloadLink.setAttribute("download", downloadFileName);
downloadLink.setAttribute("href", image);
// For some reason, we need to click the button again in firefox for the download to happen
if (navigator.userAgent.match(/Firefox/g)) {
downloadLink.click();
}
}
if (isIE) {
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, downloadFileName);
}
In the Chart.js API documentation there is a built in function called .toBase64Image() which you may wish to use instead, as you've outlined your file extension as being .png.
As Becky stated above, in Firefox, link.click() needs to be used in order for the file to download. However, the element we created (link) needs to be appended to the body of your HTML document in order for link.click() to function as required. It is important that once this statement has been executed, to remove the link element from your HTML document, so your HTML body doesn't accumulate these elements every time you try to download a chart. IE requires the canvas to be saved differently through the blob functions.
let canvas = document.getElementById('canvasId');
let chart_name = = new Chart(canvas, config);
var isIE = !!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g);
if (!isIE) {
// Create a hyperlink element.
let link = document.createElement('a');
// Set image URL and filename.
link.href = chart_name.toBase64Image();
link.download = 'IMAGE.png';
// If browser is Firefox, the element we created above must be appended to the
// body of the HTML document & therefore removed after.
if (navigator.userAgent.match(/Firefox/g)) {
document.body.append(link);
link.click();
document.body.removeChild(link);
}
}
if (isIE) {
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, 'IMAGE.png');
}

add download function to a click event with Javascript

I am wondering if it is possible to add a download function to a click event purely in Javascript, for example, when a user clicks on an image, it gets automatically downloaded. For example I have an image tag <img src="filelocation" id="img"/> and want it to be downloaded on click. (I can't use "download="myfile.png".
Is there something like
$('#img').on('click',function(e){
img.download="myfile.png";
});
All the answers online suggest adding the download="..." into my tag
Thanks!
Maybe something like this:
document.getElementById('download').click();
<a id="download" href="https://assets.entrepreneur.com/content/16x9/822/20150721193719-solshero3.jpeg" download hidden></a>
Play with it: here
But if you really can't have the download attribute: Play this then.
Good luck!!
You can create a anchor element on click of the image and use .click() to trigger the click on that anchor even if its not attach to your page.
And if this still violate the requirement, then you may have to achieve it with server-side works.
See Change name of download in javascript
window.onload = function() {
// Fake image for testment
var canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 200;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 200, 100);
ctx.fillStyle = 'cyan';
ctx.fillText('test', 50, 50);
var makeImageDownloadable = function(image, name) {
image.addEventListener('click', function() {
var a = document.createElement('a');
a.href = image.src;
// may need to check the datatype, or just write image to another tmp canvas first.
a.download = name + '.png';
a.click();
});
};
var image = new Image();
image.onload = function() {
document.querySelector('#holder').appendChild(image);
makeImageDownloadable(image, 'testimage');
};
image.src = canvas.toDataURL('image/png');
};
<div id="holder"></div>
You can use the HTML5 download attribute.
<a href="http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg" download="my_download.png"><img src="http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg">
</a>
I am unsure of browser compatibility in this,better soultion would be to include server side scripts too.
JSFiddle: http://jsfiddle.net/k2rear94/
if u want this to be dynamic, try this.
$("SomeElement").onclick = function(){
$("<a id='tmp' href='link' download ></a>).appendTo("body");
$("#tmp").click();
$("#tmp").remove();
}
But remember, download attribute is not supported in IE.

Save multiple images in canvas JQuery

Can we save the image in canvas. Like as shown in the JSFiddle.
I want to save the image in such a way the balloon should come over the image
$(document).ready(function() {
var d_canvas = document.getElementById('canvas');
var context = d_canvas.getContext('2d');
var background = document.getElementById('background');
var ballon = document.getElementById('ballon')
context.drawImage(background, 0, 0);
$('#ballon').draggable();
$('#draw').click(function() {
var $ballon = $('#ballon'),
$canvas = $('#canvas');
var ballon_x = $ballon.offset().left - $canvas.offset().left,
ballon_y = $ballon.offset().top - $canvas.offset().top;
context.drawImage(ballon, ballon_x, ballon_y);
$ballon.hide();
$(this).attr('disabled', 'disabled');
});
});
There are generally two ways to get an image from a canvas:
using getImageData() to get the rgba value for every pixel for a given rectangle of the canvas.
using toDataURL() to get a Base64 string of the entire canvas.
The second method is probably most useful, and combined with some HTML5 magic, and the download attribute, we can create a downloadable image or send the string to the server and save it as an image :
var base64 = d_canvas.toDataURL("image/png");
var a = document.createElement('a');
a.href = base64,
a.target = '_blank';
a.download = 'myImage.png';
document.body.appendChild(a);
a.click();
If you need the baloon to be in a specific place, moving that should be trivial.
Here's a
FIDDLE
Note that I had to remove the external images and use base64 to avoid cross-origin images in the canvas.

How to create a popup in Javascript?

I'm working on a web application using JSF and Javascript. I have a question about how to open a pop-up and add information into it.
Indeed, i'm using html2canvas to get the image of the content of a HTML page.
This is the code of my js :
function openPopupWithScreenshot(){
html2canvas($('#contentBody'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
window.open(img);
}
});
}
And the code of my button in JSF:
<h:commandButton value="#{bundle.button_print}" onclick="openPopupWithScreenshot();"/>
The code works perfectly, when i click on the button, a popup appears with my image. But my problem is I want to add more information (stored in a Javabean) into my popup.
Schematically, i want that my popup displays my image and a String stored in my Javabean. I'm a noob in javascript and i don't know how to do.
Could you help me please?
Thank you.
EDIT :
I have tried this :
function ouvrirPopupAvecImprEcran(){
html2canvas($('#contentBody'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
var newImg = window.open(img);
newImg.document.write("<title>TITLE</title>");
newImg.document.write("<img src='"+ img.src +"'/>");
newImg.document.write("<p>TEST</p>");
}
});
}
My popup appears correctly but my image is not display because it doesn't find the source of my image. How could i modify this?
You was almost there, try this:
function ouvrirPopupAvecImprEcran(){
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png");
var newImg = window.open();
newImg.document.write("<title>TITLE</title>");
newImg.document.write("<img src='"+ img +"'/>");
newImg.document.write("<p>TEST</p>");
}
});
}
The image you created from canvas here var img = canvas.toDataURL("image/png"); was not the HTML Element img. It was a string with data: URL, it's like an image encoded into string.
To understand it better you could look at HTMLCanvasElement#toDataURL() method here http://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement

Categories

Resources