0

I'm working on converting a canvas to an image using dataurl. I have the following code that outputs no error in console. Seems to work somewhat, but when i access the dataurl it shows a blank image.

window.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var imageObj = new Image();

    imageObj.onload = function() {
        var myImage = context.drawImage(imageObj, 0, 0);        
        var myImg = canvas.toDataURL("image/png");
        document.getElementById("canvasimg").setAttribute("src", myImg);
    };
    imageObj.src = "http://img801.imageshack.us/img801/5641/3cc67ca1a74049ce99bc92b.png";
};

<canvas id="myCanvas" width="578" height="400"></canvas>
<img id="canvasimg" alt="" src="">
Daniel
  • 4,202
  • 11
  • 50
  • 68

2 Answers2

1

Look at what you are doing. You are drawing the image when the image loads, but you are converting it to a data url before the image has been drawn! Move that toDataURL call and the setAttribute call INSIDE the onload function.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Testing the code you have posted, I get a Security Error raised. Which is to be expected. The canvas has a clean-origin flag, and once that flag is false, you can't pull data out of it.

Here's a more detailed, related question

Documentation linked to in the answer

Community
  • 1
  • 1
Shad
  • 15,134
  • 2
  • 22
  • 34