简体   繁体   中英

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM