How to send HTML <canvas> data to a server

There seem to be two ways to send <canvas> data to the server. One of them is to use canvas.getImageData() to get an array of pixels and their 8-bit color values. Another method is to use canvas.toDataURL()) to send the file attachment. This method is shown here .

I want to create a website where people can save their canvases. Which method will be more scalable and faster for my users?

+4
source share
3 answers

To open your possibilities: with fabric.js you can serialize fabric.js canvas for JSON.

It not only provides an additional level of editing capabilities, but also allows you to do the following (not to mention the ability to edit your images at a later stage):

 var canvas = new fabric.Canvas('c'); canvas.add( new fabric.Rect({ top: 100, left: 100, width: 50, height: 50, fill: '#f55' }), new fabric.Circle({ top: 140, left: 230, radius: 75, fill: 'green' }), new fabric.Triangle({ top: 300, left: 210, width: 100, height: 100, fill: 'blue' }) ); 

Now, when you want to serialize this canvas, you simply call the JSON.stringify function on the fabric canvas,

JSON.stringify(canvas);

What is an example below:

 { "objects": [ { "type": "rect", "left": 100, "top": 100, "width": 50, "height": 50, "fill": "#f55", "overlayFill": null, "stroke": null, "strokeWidth": 1, "scaleX": 1, "scaleY": 1, "angle": 0, "flipX": false, "flipY": false, "opacity": 1, "selectable": true }, ... ] } 

Serializing the canvas back to its state is canceled using:

 var canvas = new fabric.Canvas('c'); canvas.loadFromJSON(yourJSONString); 

Some additional resources:

Demo version of the kitchen sink - View the capabilities of fabric.js (including a free drawing, subsequently resizing and positioning the free drawing)

Homepage

+4
source

You can . toDataURL () it

 var datastring = document.getElementById('mycanvas').toDataURL("image/png")); 

or using jQuery

 var datastring = $('#mycanvas')[0].toDataURL("image/png"); 

And then send this line to the server via XHR, which should be the fastest.

+3
source

Try this, it works for me in the same case: -

to get json data for all canvas use JSON.stringify(canvas);

and boot from json again to use below code: -

 canvas.clear(); canvas.loadFromJSON(json_string,canvas.renderAll.bind(canvas)); 
+3
source

Source: https://habr.com/ru/post/1398772/


All Articles