atluriajith
atluriajith

Reputation: 792

canvas.todataURL doesn't work on first attempt

I am trying to draw canvas image from image source.
This below code sinppet is working fine but in IOS-- iPad-chrome and mac-safari not working for first time it is working fine from next try. Don't know where I was wrong. Please help me to get rid of this issue.

        var canvas = document.getElementById("canvasThumbResult");
        var context = canvas.getContext("2d");    
        var img = document.getElementById("ImagSrc");
        context.drawImage(img, x, y, wi, hi, 0, 0, wi, hi);
        var dataURL = canvas.toDataURL("image/jpeg");
        $("#CanvasImg").attr("src", dataURL);
        $("#CanvasImg").show(); 

Upvotes: 1

Views: 1811

Answers (1)

Simon Sarris
Simon Sarris

Reputation: 63812

You have to wait for the image to load:

    var canvas = document.getElementById("canvasThumbResult");
    var context = canvas.getContext("2d");    
    var img = document.getElementById("ImagSrc");
    if (img.complete) {
      draw();
    } else {
      img.onload = function() { draw(); };
    }

    function draw() {
      context.drawImage(img, x, y, wi, hi, 0, 0, wi, hi);
      var dataURL = canvas.toDataURL("image/jpeg");
      $("#CanvasImg").attr("src", dataURL);
      $("#CanvasImg").show(); 
    }

Upvotes: 1

Related Questions