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

Asked

Viewed 3,271 times

4

Let’s say I have a code that looks like 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 once made available on my server, a visitor uses it to make a masterpiece like this:

imagem gerada a partir do código

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

1 answer

6


You can get the image on the client side with Javascript and send it to your server with an asynchronous request (AJAX). Imagine there is a button on the page Save, that 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 event click button:

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 a direct reference to canvas 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 set in image, as string, in format image/png; Base64, then just save it to file.

You didn’t set 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.

  • when saving png it comes with transparent background. know how to tell me how to save with white background? I changed it to jpg and it was not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.