William
William

Reputation: 531

Canvas toDataURL() giving blank image

I'm a complete beginner to JS and I'm just playing around with HTML5. While experimenting, I came across this issue. I have something like this:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">
            function graph() {
                // ...stuff that draws to canvas, verified "working"...
                var downloadLink = document.getElementById("myCanvas").toDataURL();
                $("#dlLink").attr("href", downloadLink);
            }
            $(window).load(function() {
                graph();
            });
        </script>
    </head>
    <body>
        <div class="container">
            <h1 style = ";padding-bottom:30px;"><a href="#">Tool</a></h1>
            <canvas id="myCanvas" width="400" height="400"></canvas>
            <a href="#" id="dlLink">Download</a>
        </div>
    </body>
</html>

When I click the download link with the base64 encoding, I get a blank image. Can anyone bring to light why this is happening? It seems like the link is generated before the canvas has anything on it, but I can't be sure.

Upvotes: 4

Views: 5720

Answers (2)

markE
markE

Reputation: 105015

Instead, try this:

$("#dlLink").click(function(){
    var win=window.open();
    win.document.write("<img src='"+document.getElementById("myCanvas").toDataURL()+"'/>");
});

Upvotes: 3

sheng
sheng

Reputation: 1372

Try passing toDataURL a content type like "image/png" or "image/jpeg". (canvas.toDataURL("image/png"));

Upvotes: 0

Related Questions