0

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.

1
  • PHP if it's on your server JS if it's on client computer Commented Apr 12, 2017 at 10:46

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

These are both good but they need the user to download the file with a click. This looks ok, php.net/manual/en/function.imagecreatefromstring.php.
Okay, no problem. But I have made some changes based on your comment if you did want to use JS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.