简体   繁体   中英

How to save canvas as a png in localhost via a php script with the images loaded into the canvas?

I used the following function to add images to the canvas. I used fabric.js to do this.

 document.getElementById('imgLoader').onchange = function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) { console.log('fdsf');
        var imgObj = new Image();
        imgObj.src = event.target.result;


        imgObj.onload = function () {
            // start fabricJS stuff

            var image = new fabric.Image(imgObj);
            image.set({
                left: 250,
                top: 250,
                angle: 0,
                padding: 10,
                cornersize: 1
            });
            //image.scale(getRandomNum(0.1, 0.25)).setCoords();
            c.add(image);
            //context.drawImage(imgObj, 100, 100);

            // end fabricJS stuff
        }

    }
    reader.readAsDataURL(e.target.files[0]);
}

By using the above function I can succesfully add images to the canvas. But my problem is when I try to save the canvas as an image, it gives a blank image. I used the below code to convert the canvas to an image.

var canvas = document.getElementById('c');  //Id of the canvas
var dataURL = canvas.toDataURL();    
$('#saveMe').click(function() {    
         $.ajax({
                type: "POST",
                url: "myscript.php",
                data: {
                    img: dataURL
                }
            }).done(function(o) {
                console.log('saved');

            });

myscript.php is as below.

define('UPLOAD_DIR', 'C:/xampp/htdocs/pic/');
chmod(UPLOAD_DIR, 777);
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

Even though I added images to the canvas, when saving, I get only the blank canvas, not getting the image I have loaded into the canvas. Please help me.Thanks in advance.

Use fileSaver.js ,its very handy . You can also see a demo here http://eligrey.com/demos/FileSaver.js/

Implementation

    $(function () {
        $("#btnSave").click(function () {
            html2canvas($("#widget"), {
                onrendered: function (canvas) {
                    canvas.toBlob(function (blob) {
                        saveAs(blob, "Dashboard.png");
                    });
                }
            });
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM