Reputation: 625
I'm programming a game with socket.io drawing in an HTML5 canvas and when the time is over send the image to the node.js server. Is there some way to convert that canvas in an image, send the image in base64 to the node.js app, an finally save it into the server?
Upvotes: 3
Views: 3232
Reputation: 1193
Yes, the canvas
element provides a method named toDataURL()
. This method returns a data:
URL which includes the base64 representation of the image in the specified format, or PNG by default:
var canvas = document.getElementsByTagName('canvas')[0];
var dataUrl = canvas.toDataURL();
Assuming you are using socket.io, you can send this data URI over the socket by emitting an event:
var socket = io.connect('http://localhost');
socket.emit('image', dataUrl);
On the Node side, you can listen to this event on the socket to retrieve the image:
io.sockets.on('connection', function (socket) {
socket.on('image', function (dataUrl) {
console.log(dataUrl);
});
});
You can then trim the prefix data:image/png;base64,
if necessary and upload the content to a server.
Read more on the MDN documentation for the canvas
element.
Upvotes: 3