views:

45

answers:

2

Hi,

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 ?

A: 

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;
Gleb M Borisov
I want to show the image in another canvas not as image
Riyas Anchal
You always could construct image from base64 encoded data and put it on canvas.
Gleb M Borisov
Check updated version of answer to see decoding example.
Gleb M Borisov
A: 

Thanks Gleb,

But I want to show the image in another canvas not as image. I tried your script, I can pass it through ajax, but can't display it in another canvas. Any other solution to show it in canvas ?

Regards, Riyas

Riyas Anchal