0

Hey so I have looked around and have been able to convert my canvas into an dataURL and download it using this function:

function downloadImage(data, filename = 'untitled.jpeg') {
    var a = document.createElement('a');
    a.href = data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}

where

data = canvas.toDataURL("image/jpeg")

but I didn't find any way to convert the canvas into an image link which I could share with other people around the globe. Maybe a post method has to be applied and how could it be? I can also use a node.js online server

Woold
  • 783
  • 12
  • 23

1 Answers1

2

Assuming that data = canvas.toDataURL("image/jpeg"), you can specify a base64 link with the correct headers :

const canvas = document.querySelector('canvas')
const button = document.querySelector('button')
const ctx = canvas.getContext('2d')

canvas.width = window.innerWidth
canvas.height = window.innerHeight

ctx.fillStyle = 'red'
ctx.fillRect(50, 50, 100, 100)

button.addEventListener('click', () => {
  let data = canvas.toDataURL("image/jpeg");
  data = data.replace('data:image/jpeg;base64,', '')
  console.log(data)
  downloadImage(data);
})

function downloadImage(data, filename = 'untitled.jpeg') {
    const a = document.createElement('a');
    a.href = 'data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=' + filename + ';base64,' + data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}
<button>Save</button>
<canvas></canvas>

Source: HTML5 Canvas to PNG File

Treast
  • 1,095
  • 1
  • 9
  • 20
  • this method works but the text file is quite long and I'd like to share it with socket.io (websocket) to other clients, do you know any way to make that easier? @Treast – Woold Jun 01 '20 at 18:49
  • The base64 is one of the easier method to send an image on socket, because it's just a string to send. If the string is too long, you can try to resize the canvas before getting DataURL, or you can reduce the quality of the JPEG `let data = canvas.toDataURL("image/jpeg", 0.4); // 40% for example`. – Treast Jun 01 '20 at 18:53
  • i've just been using that, (i know its been awhile but i was planning in advance for a project) and it seems like the percentage of quality doesn't affect the quality, I have compared a canvas.toDataURL("image/jpeg", 1) and a canvas.toDataURL("image/jpeg", 0.01) and the size of the string and the quality are the same, do you know where the issue come from please? – Woold Jun 08 '20 at 10:42