Page 1 of 1

AJAXing an HTML5 bitmap to the server

Posted: Mon Aug 01, 2011 7:17 pm
by Jackolantern
While I realize this will probably be of limited use to most people, when you need it, you need it. I spent quite a while trying to get this worked out, but finally have it up and running. The basic premise is that you can create a bitmap of the HTML5 canvas at any time with the canvas.toDataURL() JS method, but then your bitmap is on the client. To send it back to the server and save it in a folder called "images", you can use code like this:

(note: while jQuery isn't needed for this small example, it is used because I will be using it in my project)

canvas HTML5 file:

Code: Select all

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Make and send PNG</title>
    <script type="text/javascript" src="jquery141.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var canvas = document.getElementById('myCanvas');
            var context = canvas.getContext('2d');
            context.fillStyle = '#ffffaa';
            context.fillRect(0, 0, 500, 400);
            context.fillStyle = '#ff0000';
            context.font = '14px _sans';
            context.fillText('Woo hoo! Man...', 220, 200);
            
            $('#myButton').click(function() {
                var img = canvas.toDataURL("image/png");
                
                $.post('makefile.php', {data: img}, function(evt) {
                            alert("File was sent");
                        });
                
                
                
            });
            
        });
    </script>
</head>

<body>
<canvas id="myCanvas" width="500" height="400">
    No canvas support. Get a new freakin' browser.
</canvas>
<form>
    <input type="button" id="myButton" value="Save" />
</form>


</body>
</html>
And the PHP serverside script that saves the image:

Code: Select all

<?php
    $imgFile = $_POST['data'];
    $codedImg = base64_decode(substr($imgFile, strpos($imgFile, ",")+1));
    //not using file_put_contents() for PHP4 compatiblity
    $fp = fopen("images/backimage.png", 'w');
    fwrite($fp, $codedImg);
    fcloser($fp);
?>