Jump to content

Saving canvas image to server


oz11

Recommended Posts

How would I go about using the script bellow to save the updated image to serverside using PHP

<html>
    <script type="text/javascript">
    var canvas, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        dot_flag = false;

    var x = "black",
        y = 2;

    var saveTimer;
    function onSaveTimer() {
          save();              
    }


    function init() {
        canvas = document.getElementById('can');
        ctx = canvas.getContext("2d");
        w = canvas.width;
        h = canvas.height;

        canvas.addEventListener("mousemove", function (e) {
            findxy('move', e)
        }, false);
        canvas.addEventListener("mousedown", function (e) {
            findxy('down', e)
        }, false);
        canvas.addEventListener("mouseup", function (e) {
            findxy('up', e)
        }, false);
        canvas.addEventListener("mouseout", function (e) {
            findxy('out', e)
        }, false);
        
       saveTimer = setInterval(onSaveTimer, 3000);
    }

    function color(obj) {
        switch (obj.id) {
            case "black":
                x = "black";
                break;
            case "white":
                x = "white";
                break;
        }
        if (x == "white") y = 14;
        else y = 2;

    }

    function draw() {
        ctx.beginPath();
        ctx.moveTo(prevX, prevY);
        ctx.lineTo(currX, currY);
        ctx.strokeStyle = x;
        ctx.lineWidth = y;
        ctx.stroke();
        ctx.closePath();
    }

    function erase() {
        var m = confirm("Want to clear");
        if (m) {
            ctx.clearRect(0, 0, w, h);
            document.getElementById("canvasimg").style.display = "none";
        }
    }

    function save() {
        
        document.getElementById("canvasimg").style.border = "2px solid";
        var dataURL = canvas.toDataURL();
        if (dataURL) { 
            document.getElementById("canvasimg").src = dataURL;
            document.getElementById("canvasimg").style.display = "inline";
            return true; // will POST form to the server
        }
        return false; // will not POST to server

    }

    function findxy(res, e) {
        if (res == 'down') {
            prevX = currX;
            prevY = currY;
            currX = e.clientX - canvas.offsetLeft;
            currY = e.clientY - canvas.offsetTop;

            flag = true;
            dot_flag = true;
            if (dot_flag) {
                ctx.beginPath();
                ctx.fillStyle = x;
                ctx.fillRect(currX, currY, 2, 2);
                ctx.closePath();
                dot_flag = false;
            }
        }
        if (res == 'up' || res == "out") {
            flag = false;
        }
        if (res == 'move') {
            if (flag) {
                prevX = currX;
                prevY = currY;
                currX = e.clientX - canvas.offsetLeft;
                currY = e.clientY - canvas.offsetTop;
                draw();
            }
        }

        }
    </script>
    <body onload="init()">
        <canvas id="can" width="500px" height="150px" style="position:absolute;border:2px solid;"></canvas>
        <div style="position:relative;top:30px;left:520px;">Eraser</div>
        <div style="position:relative;top:40px;left:520px;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>
        <div style="position:relative;top:70px;left:520px;width:15px;height:15px;background:black;border:2px solid;" id="black" onclick="color(this)"></div>
        <div style="position:relative;top:30px;left:520px;">Pen</div>
<form method="POST" action="" onsubmit="save">
        <img id="canvasimg" style="position:relative;top:10%;left:600px;" style="display:none;">
</form>
        <!--<input type="button" value="save" id="btn" size="30" onclick="save()" style="position:fixed;top:170px;left:10px;">-->
       <!-- <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:fixed;top:170px;left:60px;">-->
    </body>
    </html>
  

I was thinking something along the lines of POST in PHP..?.. no?..

Screenie for illustration:

 

Screenshot from 2023-05-09 22-42-19.png

Edited by oz11
Btw. It's code I found and modified.
Link to comment
Share on other sites

I found this... https://www.rgraph.net/canvas/reference/todataurl.html#:~:text=The toDataURL function returns a,save it to a file. which looks great. Don't know how to amend them together yet, both the codes.. help..? Could someone splice them for me.. ?

 

This also looks handy: 

$dataURL = $_POST["imageDataURL"];
$dataURL = str_replace('data:image/png;base64,', '', $dataURL);
$dataURL = str_replace(' ', '+', $dataURL);
$image = base64_decode($dataURL);
$filename = 'newImage.png';
file_put_contents('path/to/' . $filename, $image);

But how do the pieces fit together..?

Edited by oz11
Link to comment
Share on other sites

Canvas has a toBlob method, which allows you to create an image file from the canvas as a JavaScript Blob object.  You can then upload that blob to your server using the FormData object and fetch().

Something like this:

function uploadCanvas(canvas, url){
  canvas.toBlob((blob)=>{
    const data=new FormData();
    data.append('canvas', blob);
    fetch(url, {method: 'post', body: data});
  });
}

On the PHP side of things, you handle it just like any other file upload by looking at $_FILES['canvas'] and saving it as desired.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.