Passing canvas data through ajax
I have an application to save the canvas data instantaneously to server. My requirement is to export the canvas data on every second, save it to the server through ajax and import the same data to another canvas in another browser through ajax. I am using Jquery for ajax. I used the following code to pass the data
function sendCanvasData() {
var data = '';
var ctx = document.getElementById('imageView').getContext('2d');
data = ctx.getImageData(0, 0, 250, 250);
$.post("canvas.php", {
cdata: data
});
}
But it passing a null value to the server. How can开发者_运维百科 I do this ?
You can get data URL for this image.
document.getElementById('imageView').toDataURL('image/png')
Return value will be Base64-encoded image data in PNG. You can upload this data to server.
Also you can show this data to clients without any transformations or convertations (<img src="data:..."/>
).
When you load this data from server, just decode and put image on canvas:
var img = new Image();
img.onload = function () {
canvas.getContext('2d').drawImage(this, 0, 0);
}
img.src = base64EncodedData;
精彩评论