Saving canvas to a file

I need to save canvas to a file inside a server directory to process it later in another program. When I use saveCanvas() browser creates a prompt window. How can I save a file to a specified directory without a prompt window?

you can save it only locally on your PC,
but could upload it later ( to /data/ /assets/ )

  • Browsers don’t allow scripts to save files locally w/o prompting the user!
  • Browsers do have a local storage. But it’s too small for anything larger than small text files AFAIK.
  • However, if you have access to a file server, you can save files there w/o user permission.

I think most browsers have a setting where you can dictate what happens for each file type that could be downloaded. So, if my processing script is saving a canvas to XXX.png, I’ll have changed the settings in the browser to save all .png’s to a given folder. In Firefox, go to Settings>General.

I think you can’t do this without some serverside functions. In a project I used PHP to save the canvas as images.

Here are the crucial parts of my code.
index.php where the sketch is displayed.
server.js to get the image data from the sketch and submit it in a form.
upload.php to call some magic on the server.

Maybe I missed something, its been a while.
And If someone likes to recommend improvements, feel free.
Also I changed some variable names before posting this.

index.php

<button name="submit" type="submit" onClick="exportImage()">Send</button>

server.js

// Save and Upload Image
function saveImage() {
    console.log("Start saving...");
    let defaultCanvas = document.getElementById("defaultCanvas0");
    let dataURL = defaultCanvas.toDataURL("image/png");
    let progressBar = document.querySelector("#progressBar");

    document.getElementById("hidden_data").value = dataURL;
    document.getElementById("hidden_no").value = idNumber.split(".").join("-");
    let formData = new FormData(document.forms["uploadForm"]);

    let xhr = new XMLHttpRequest();
    xhr.open("POST", "upload.php", true);

    xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            let percentComplete = (e.loaded / e.total) * 100;
            let completion = document.getElementById("submitscreen");

            progressBar.style.width = percentComplete + "%";
            console.log(percentComplete + "% uploaded");

            let body = document.getElementById("body");
            body.classList.add("locked");
            body.scrollTop = 0;
            document.documentElement.scrollTop = 0;

            if (percentComplete == 100) {
                progressBar.style.width = "0%";
                completion.classList.add("shown");

                setTimeout(function () {
                    window.open("results.php?idNumber="+idNumber.split(".").join("-"),"_self");
                }, 2500);
            }
        }
    };

    xhr.onload = function () {

    };
    xhr.send(formData);
};

upload.php

<?php
    
    // Upload destination
    $upload_dir = "images/";
    $img = $_POST['hidden_data'];
    $id = $_POST['hidden_id'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);

    // Create and write file
    $data = base64_decode($img);
    $file = $upload_dir . $id . "-". mktime() . ".png";
    $thumb = $thumb_dir . $id . "-". mktime() . ".png";
    $success = file_put_contents($file, $data);


    // Make thumbnail
    function make_thumb($src, $dest, $desired_width) {

        print("make_thumb");

        /* read the source image */
        $source_image = imagecreatefrompng($src);
        $width = imagesx($source_image);
        $height = imagesy($source_image);

        /* find the "desired height" of this thumbnail, relative to the desired width  */
        $desired_height = floor($height * ($desired_width / $width));

        /* create a new, "virtual" image */
        $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

        /* copy source image at a resized size */
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

        /* create the physical thumbnail image to its destination */
        imagepng($virtual_image, $dest);
    }

    // Call thumbnail creation
    make_thumb($file, $thumb, 240);


    // Print if upload fails...
    print $success ? $file : 'Unable to save the file.';
?>