html2canvas output selected div PHP

吃可爱长大的小学妹 提交于 2019-12-21 22:38:43

问题


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


回答1:


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());
        }
    });
});



回答2:


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']?



来源:https://stackoverflow.com/questions/10778105/html2canvas-output-selected-div-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!