Is it possible to save the canvas as image, and send it to the server?

3

Let's say I have code similar to this:

<html>
    <head>
        <style>
            .centralizado {
                position: fixed;
                top: 50%; 
                left: 50%; 
                transform: translate(-50%, -50%);
            }
        </style>
    </head>
    <div>
        <canvas class="centralizado" id="canvas">your browser is nope!</canvas>
    </div>
    <script>
        function init() {
            var ctx = document.getElementById("canvas").getContext('2d');
            ctx.canvas.width  = window.innerWidth;
            ctx.canvas.height = window.innerHeight;
            var pinta = false;
            var red = green = blue = 127;
            var rf = 1, gf = 1, bf = 1;
            var rm = getAleatorio();
            var gm = getAleatorio();
            var bm = getAleatorio();

            function desenha(e) {
                var pos = getPosMouse(canvas, e);
                posx = pos.x;
                posy = pos.y;
                if (pinta) {
                    ctx.fillStyle = "rgb(" + red + ", " + green + ", " + blue + ")";
                    ctx.fillRect(posx-4, posy-4, 8, 8);
                }
            }

            canvas.onmousemove = function(e) {
                desenha(e);
                red += rm * rf;
                green += gm * gf;
                blue += bm * bf;

                if (red >= 255 || red <= 0) { rf *= -1; rm = getAleatorio();}
                if (green >= 255 || green <= 0) { gf *= -1; gm = getAleatorio();}
                if (blue >= 255 || blue <= 0) { bf *= -1; bm = getAleatorio();}

            };

            document.getElementById("canvas").onmousedown = function() {
                pinta = true;
            };

            document.getElementById("canvas").onmouseup = function() {
                pinta = false;
            }

            function getPosMouse(canvas, evt) {
                var rect = canvas.getBoundingClientRect();
                return {
                    x: evt.clientX - rect.left,
                    y: evt.clientY - rect.top
                };
            }

            function getAleatorio() {
                return Math.floor((Math.random() * 5) + 1);
            }
        }
    </script>
    <body onLoad="init();">
</html>

And as soon as it is made available on my server, a visitor will use it to make a masterpiece like this:

  

How do I allow the user to save the drawing he does, not locally, but on my server?

    
asked by anonymous 07.05.2017 / 11:07

1 answer

4

You can get the client-side image with JavaScript and send it to your server with an asynchronous request (AJAX). Imagine there is a Save button on the page, which when the user presses, sends the current image to the server and saves it.

<button id="saveBtn" type="button">Salvar</button>

We can add the following function to the button's click event:

const saveBtn = document.getElementById("saveBtn");
const canvas = document.getElementById("canvas");

saveBtn.onclick = function (e) {
    var http = new XMLHttpRequest();

    // Converte o canvas para image/png; base64:
    var image = canvas.toDataURL()

    // Define a imagem como valor a ser enviado:
    var params = "image=" + image; 

    http.open("POST", "http://localhost/save", true);
    http.setRequestHeader("Content-type", "text/plain"); // Talvez o Content-type pode ser outro, não tenho certeza quanto a isso

    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert("Imagem salvada com sucesso");
        }
    }

    http.send(params);
}
  

Note that in this case the direct reference to canvas is required and not just the context of it, then you will have to add the following line to your code:

     

const canvas = document.getElementById("canvas");

So, on your server, through the URL http://localhost/save , you will receive the image through the value defined in image , as string , in the format image / png; base64 , then just save it to a file.

You did not define the language used on the server, but for example, in PHP it would look something like:

$data = $_POST["image"];

list($type, $data) = explode(';', $data);
list($base, $data) = explode(',', $data);

$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

Creating the image /tmp/image.png with the contents of the canvas.

    
07.05.2017 / 15:57