Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to store the rendered image from canvas ? #115

Closed
mrsrinivas opened this issue Jul 21, 2012 · 18 comments
Closed

How to store the rendered image from canvas ? #115

mrsrinivas opened this issue Jul 21, 2012 · 18 comments

Comments

@mrsrinivas
Copy link

Hi niklasvh,
I am developing a website on PHP(Codeigniter). In that i am using html2canvas tool to capture screen shot of a website. Its working fine. But need to to store the image in my web server ?

Is it possible with this tool?

@mrsrinivas
Copy link
Author

@niklasvh
Copy link
Owner

You can call the toDataUrl method on the canvas, to get it as a base64 encoded string, which you can then send to the server using ajax.

@mrsrinivas
Copy link
Author

for this code alert( $("#content").html());

its displying

<canvas height="677" width="1007" style="width: 1007px; height: 677px;"></canvas>

and

$("#content").empty().append(j);
alert(j.toDataUrl());

it's giving the error TypeError: j.toDataUrl is not a function
Here j is HTMLCanvasElement

@niklasvh
Copy link
Owner

What browser are you using, i.e. does it have native canvas support or is it using FlashCanvas, as flashcanvas has some issues with toDataUrl (see #97)?

Is j actually HTMLCanvasElement or a jQuery wrapped HTMLCanvasElement? If its the latter, then try j[0].toDataUrl or j.get(0).toDataUrl

@mrsrinivas
Copy link
Author

<script src="http://code.jquery.com/jquery.min.js"></script> 
<script type="text/javascript" src="http://html2canvas.hertzen.com/js/html2canvas.js?rev032"></script> 
<script type="text/javascript">
    var date=new Date();
    var message,timeoutTimer,timer;
    var proxyUrl="http://html2canvas.appspot.com";

    function addRow(a,c,d){var b=$("<tr />").appendTo($(a));b.append($("<td />").css("font-weight","bold").text(c)).append($("<td />").text(d))}

    function throwMessage(b,a){
        window.clearTimeout(timeoutTimer);
        timeoutTimer=window.setTimeout(function(){
            message.fadeOut(function(){message.remove()})
        },
        a||2000);

        $(message).remove();
        message=$("<div />").html(b).css({
            margin:0,
            padding:10,
            background:"#000",
            opacity:0.7,
            position:"fixed",
            top:10,right:10,
            fontFamily:"Tahoma",
            color:"#fff",
            fontSize:12,
            borderRadius:12,
            width:"auto",
            height:"auto",
            textAlign:"center",
            textDecoration:"none"
        }).hide().fadeIn().appendTo("body");
    }

    $(function(){$("#recommended a").click(function(c){
            c.preventDefault();
            $("#url").val(this.href);
            $("button").click()
        });

        var a,b;$('input[type="button"]').click(function(){$(a.contentWindow).unbind("load");$(a).contents().find("body").html2canvas({canvasHeight:b.body.scrollHeight,canvasWidth:b.body.scrollWidth,logging:true})});

        $("#getscreenshot").click(function(d){
            d.preventDefault();
            $(this).prop("disabled",true);
            var c=$("#url").val();
            $("#content").append($("<img />").attr("src","http://html2canvas.hertzen.com/loading.gif").css("margin-top",40));
            var f=document.createElement("a");
            f.href=c;
            $.ajax({
                data:{xhr2:false,url:f.href},url:proxyUrl,dataType:"jsonp",success:function(e){
                    a=document.createElement("iframe");
                    $(a).css({visibility:"hidden"}).width($(window).width()).height($(window).height());
                    $("#content").append(a);
                    b=a.contentWindow.document;
                    b.open();$(a.contentWindow).load(function(){
                        var g=$(a).contents().find("body"),h={onrendered:function(j){


                            $("#content").empty().append(j);                            

                            alert(j[0].toDataUrl());

                            $("#getscreenshot").prop("disabled",false);
                            $("base").attr("href","")
                        }, 
                        allowTaint:true,
                        taintTest:false,
                        flashcanvas:"src/flashcanvas.min.js"},
                        i=html2canvas(g,h)
                    });
                    $("base").attr("href",f.protocol+"//"+f.hostname+"/"+f.pathname);
                    e=e.replace("<head>","<head><base href='"+f.protocol+"//"+f.hostname+"/"+f.pathname+"'  />");

                    if($("#disablejs").prop("checked")){
                        e=e.replace(/\<script/gi,"<!--<script");
                        e=e.replace(/\<\/script\>/gi,"<\/script>-->")
                    }
                    b.write(e);b.close()
                }
            });
        })
    });
</script> 

<h1>Html2Canvas javaScript screenshot creator</h1>
<form class="well form-search"> <label for=url>Website URL:</label> 
    <input type=url id=url value="http://www.google.co.in" class="input-medium search-query"/><button class=btn id=getscreenshot>Get screenshot!</button> 
</form> 
<label for="disablejs">Disable JavaScript (recommended, doesn't work well with the proxy)</label>
<input id="disablejs" type="checkbox" checked="">
<br>
<div id=content></div> 

This is the total code i am using. It is just taken from html2canvas demo

I am using Firefox 14.0.1 for Windows..

@pcottle
Copy link

pcottle commented Aug 3, 2012

@niklasvh @mrsrinivas for some bizarre reason, Chrome changed the method to getDataURL(). Note the case change... :O

Lost a good half hour on this! Hope that helps

@niklasvh
Copy link
Owner

niklasvh commented Aug 3, 2012

Thanks for the heads up

@BruceDai
Copy link

hi,mrsrinivas .How is this issue going? Was it able to store the screenshot? If it works, would you please share your experience with me , thanks.

@mrsrinivas
Copy link
Author

still i'm not able to get the url of image file in any format.

@halburgiss
Copy link

This worked for me with v0.34 ...

$('button').on( 'click', function() {
    var screenshot = {};
    html2canvas( [ document.getElementById( 'main-container' ) ], {
        onrendered: function( canvas ) {
            screenshot.img = canvas.toDataURL( "image/png" );
            screenshot.data = { 'image' : screenshot.img };
            $.ajax({
                url: "/image_handler.php",
                data: screenshot.data,
                type: 'post',
                success: function( result ) {
                    console.log( result );
                }
            });
            }
    });
});

// php
$result = file_put_contents( 'myimage.png', base64_decode( str_replace('data:image/png;base64,','',$_POST['image'] ) ) );

@proseox
Copy link

proseox commented Dec 24, 2012

@halburgiss - in which file an where exactly must the code include?

@vishnued
Copy link

vishnued commented Mar 4, 2014

canvas.toDataURL( "image/png" ); throwing security exception while capturing google map

@rchawdhari
Copy link

If i want to take screenshot and store it into pdf file.how could i do this?

@Onwuasoanya-George
Copy link

thanks alot halburgiss.
Code:
JS:
html2canvas(document.getElementById('userStats'), {
onrendered: function(canvas) {
document.body.appendChild(canvas);
var screenshot = {};
screenshot.img = canvas.toDataURL( "image/png" );
screenshot.data = { 'image' : screenshot.img };

       $.ajax({

            type: "POST",
            url: "savePNG.php",
            data: screenshot.data,
            success : function(data)
            {
                console.log("screenshot done");
            }
        }).done(function() {
            //$('body').html(data);
        });

        }
    });

PHP (savePNG.php)
$image = $_POST['image'];
$filedir = "images/png";
$name = time();

$image = str_replace('data:image/png;base64,', '', $image);
$decoded = base64_decode($image);

file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX);

@deb54
Copy link

deb54 commented Jun 11, 2017

I have used your code. It shows:
Uncaught (in promise) DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
at http://localhost/Blog/:313:24
at

@eKoopmans
Copy link
Contributor

Hi @deb54, "tainted canvases" are a result of cross-domain images. For Internet security reasons, trying to use an image from a different domain in a canvas causes problems. There are two html2canvas options, useCORS and proxy, which are designed to try to get around that problem. They're not perfect solutions though - you can read more over at #951 and #592.

@deb54
Copy link

deb54 commented Jun 18, 2017

Thanks, eKoopmans. Actually, me trying to save the total div as an image. Now I have faced two new problems, after converting Html to canvas the image size is fixed, i can't resize the canvas, if I resize then it appears blank.

@Mvhd
Copy link

Mvhd commented Sep 26, 2018

Hi all, storing canvas.toDataUrl() in CodeIgniter:

Jquery, Ajax, download [htm2canvas.min.js](https://html2canvas.hertzen.com/)

 html2canvas($('#targetDiv')[0]).then(function(canvas) {
            var dataUrl = canvas.toDataURL();
           var newDataURL = dataUrl.replace(/^data:image\/png/, "data:application/octet-stream"); //do this to clean the url.
           $("#saveBtn").attr("download", "your_pic_name.png").attr("href", newDataURL); //incase you want to create a download link to save the pic locally.
      
        $.ajax({
            'type': 'post',
            'url': 'link_to_function_in_controller',
            data: {
                //you can more data here
                'img':newDataURL
            },
            success: function(data){
                console.log(data);
            },
            error: function(data){
                console.log(data);
            }
        });
        
        });


// in your codeigniter controller
        
            $img = $this->input->post('img'); //get the image string from ajax post
            $img = substr(explode(";",$img)[1], 7); //this extract the exact image
            $target=time().'_img.png'; //rename the image by time
            $image = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/imagefolder/'.$target, 
           base64_decode($img)); //put the image where your image folder directory is located
            
            $data = array(
                'Image' => $target, //note you can add more data
                'date_inserted' => mdate('%Y-%m-%d %H:%i:%s', now())
            );
            
            $result = $this->model_image->post_image($data); //post_image() here should be your function in codeigniter model layer that handles the database, while the model_image is the model name itself where post_image() draws its properties from

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests