LeBlaireau
LeBlaireau

Reputation: 17467

Canvas - saving to image with php or js

I have a canvas element and want to name it and save it as a jpg in my file system.

var canvas = document.getElementById("myCanvas");
var dataURL = canvas.toDataURL();
console.log(dataURL)

I can use either PHP or JS.

Is this possible? It seems like it should be easy.

Upvotes: 0

Views: 62

Answers (2)

DibsyJr
DibsyJr

Reputation: 874

This solution will work if the element you want to bind the click event to already exists:

var url = canvas.toDataURL();
var link = document.getElementById('-insert a element id here');
link.download = "DownloadName";
link.href = url;

This will create the data url, then assign it to the href of whatever link you have if it already exists, you just need to replace '-insert a element id here' with the id of the link you want it to be assigned to.

Alternatively if it doesn't exist you could do:

var url = canvas.toDataURL();
var link = document.createElement('a');
link.download = "DownloadName";
link.href = url;
link.innerHTML = "Download";
document.getElementById('-insert parent element here-').appendChild(link);

This will create the data url, then create an a element, set its download, href and innerHTML properties and insert it in the DOM. Just replace '-insert parent element here-' with whatever element you want the link to be inside.

Upvotes: 0

Vinod Louis
Vinod Louis

Reputation: 4876

You can try this

Getting url as base64 create a dynamic link with hreaf as data url and click to force download and then remove link

var canvas = document.getElementById("myCanvas");
var dataURL = canvas.toDataURL();
console.log(dataURL);

 var e = document.createElement('a');
        var href = dataURL
        e.setAttribute('href', href);
        e.setAttribute('download', "FILE NAME.png");
        document.body.appendChild(e);
        e.click();
        document.body.removeChild(e);
<canvas id="myCanvas"></canvas>

Upvotes: 1

Related Questions