Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas.toDataURL() not working properly [duplicate]

I am having a canvas in which I upload an image with the following code:

function handleImage(e){
    var reader = new FileReader();
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img,0,0);
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);
}

Now I wanted to use the canvas.toDataURL() to load the image to another canvas. The code is:

var dataURL = canvas.toDataURL();
drawDataURIOnCanvas(dataURL,canvas2);

    function drawDataURIOnCanvas(dataURL, name_of_canvas) {

    var myCanvas = document.getElementById(name_of_canvas);
    var img3 = new Image;
    var ctx2 = myCanvas .getContext('2d');
    img3.onload = function(){
       ctx2.drawImage(img3,0,0); // Or at whatever offset you like
    };
    img3.src = dataURL;
}

If I put to this a working url all fine. But the produced url from any picture I have tried comes out as

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAxUlEQVR4nO3BMQEAAADCoPVPbQhfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOA1v9QAATX68/0AAAAASUVORK5CYII=.

If you try to use that it would not produce the photo of a plane that was in the canvas. How can I use the function toDataURL to draw the image on another canvas?

like image 682
mpla_mpla Avatar asked Jun 20 '15 07:06

mpla_mpla


People also ask

Is toDataURL synchronous?

toDataURL is a synchronous operation that does not trigger any events. Being synchronous, it's a blocking operation so no alert is required to prevent the next command from executing before toDataURL is fully complete. The next command will execute when toDataURL is fully complete.

What is canvas toDataURL?

toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter. The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png .


1 Answers

You can look at example of using HTMLCanvasElement.toDataURL() at developer.mozilla.org

toDataURL returns valid base64 encoded image. So the problem is how you assign this image for second canvas.

like image 183
outoftime Avatar answered Sep 27 '22 18:09

outoftime