2

this code almost works
this will output the entire page into a jpg
question: how can i grab only the content inside '#myDiv' and output that as a jpg file?

JS:

$('.myButton').click(function(){
    $('#myDiv').html2canvas();//<< has no effect
    var queue = html2canvas.Parse();
    var canvas = html2canvas.Renderer(queue,{elements:{length:0}});
    var img = canvas.toDataURL();
    img.replace(/^data:image\/(png|jpg);base64,/, "");
    $.post( "postIO.php", {img:img}, function(data) {
        //$('#recieve').append(data);
    }); 
    return false;
});

postIO.php:

$canvasImg = $_POST['img'];    
//$canvasImg = str_replace('data:image/png;base64,', '', $canvasImg);

$data = base64_decode($canvasImg);
$File = "z.jpg"; 
$Handle = fopen($File, 'w');
fwrite($Handle, $data);  
fclose($Handle);

reference from here

Community
  • 1
  • 1
t q
  • 4,593
  • 8
  • 56
  • 91

2 Answers2

3

I have download and try html2canvas, then I find out the jquery plugin does not complete (it's does nothing than capture the image and create canvas, no use) so I write capture code myself.

var el = $('div').get(0);

function saveData(dturl){
    //Upload here
    console.debug(dturl);
}

html2canvas.Preload(el, {
    complete: function(image){
        var queue = html2canvas.Parse(el, image, {elements: el}),
            $canvas = $(html2canvas.Renderer(queue, {elements: el}));
        saveData($canvas[0].toDataURL());
    }
});

Hope it help you

so to use with your program you have to write

function saveData(dturl){
    dturl.replace(/^data:image\/(png|jpg);base64,/, "");
    $.post( "postIO.php", {img:dturl}, function(data) {
        //$('#recieve').append(data);
    }); 
}

$('.myButton').click(function(){
    var el = $('#myDiv').get(0); 
    html2canvas.Preload(el, {
        complete: function(image){
            var queue = html2canvas.Parse(el, image, {elements: el}),
                $canvas = $(html2canvas.Renderer(queue, {elements: el}));
            saveData($canvas[0].toDataURL());
        }
    });
});
James
  • 13,571
  • 6
  • 61
  • 83
1

after var canvasImg = canvasRecord.toDataURL("image/jpg");, you may need to replace it using var data = canvasImg.replace(/^data:image\/(png|jpg);base64,/, "");

and is that $canvasImg = $_POST['canvasImg']; instead of $_POST['img']?

Abby Chau Yu Hoi
  • 1,378
  • 3
  • 15
  • 37