html2canvas输出选中div PHP

时间:2012-05-27 23:58:55

标签: php javascript jquery html2canvas

这段代码几乎可以工作 这会将整个页面输出到jpg中 问题:我如何只抓取'#myDiv'内的内容并将其输出为jpg文件?

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

来自here

的参考资料

2 个答案:

答案 0 :(得分:3)

我已经下载并尝试了html2canvas,然后我发现jquery插件没有完成(它没有什么比捕获图像和创建画布,没有用)所以我自己编写捕获代码。

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

希望对你有帮助

所以要与你的程序一起使用,你必须写

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

答案 1 :(得分:1)

var canvasImg = canvasRecord.toDataURL("image/jpg");之后

,您可能需要使用var data = canvasImg.replace(/^data:image\/(png|jpg);base64,/, "");

替换它

并且是$canvasImg = $_POST['canvasImg'];而不是$ _POST ['img']?