On a canvas, difference between drawImage with png

2019-07-20 15:11发布

问题:

Why is there a difference between how things are handled in a canvas? E.g if I put a png on the canvas vs draw a line on the canvas. When I copy that canvas's content to another canvas, only the line gets copied over.

var thecanvas = document.getElementById('mycanvas');
var context = thecanvas.getContext('2d');

// put a png on the canvas
var img = new Image();
img.onload = function(){ context.drawImage(img,0,0); };
img.src = 'images/test.png';        

// draw a line on the canvas
context.moveTo(100, 150); context.lineTo(450, 50); context.stroke();

final_image = thecanvas.toDataURL("image/png");
copyimg = new Image();
copyimg.src = final_image;          
var newcanvas = document.getElementById('newCanvas');
var newcanvascontext = newcanvas.getContext('2d');

// why is only the line I drew copied over and not the png image???
newcanvascontext.drawImage(copyimg,0,0,397,397);

回答1:

Please note the image load event. Canvas is copied before the image gets loaded. You have to do like this

var thecanvas = document.getElementById('mycanvas');
var context = thecanvas.getContext('2d');

// put a png on the canvas
var img = new Image();
img.onload = function(){ 

        context.drawImage(img,0,0); 

        var newcanvas = document.getElementById('newCanvas');
        var newcanvascontext = newcanvas.getContext('2d');
        newcanvascontext.drawImage(thecanvas,0 ,0);

};
img.src = 'http://www.mygreatiphone.com/wp-content/uploads/2011/11/google.png';        

// draw a line on the canvas
context.moveTo(100, 150); context.lineTo(450, 50); context.stroke();

See the demo : http://jsfiddle.net/diode/3NHXy/5/