Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Image in Canvas using DataURL

I am trying to create 3 canvas.

  • The first canvas consist of image1.
  • The second canvas consist of image2.
  • The third canvas is a canvas that I want to use javascript to draw the image1 from DataURL().

However, I couldn't able to draw it. Is there anything I did wrong?

HTML code

<body>
<img id="image1" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas"></canvas>

<img id="image2" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">
<canvas id="myCanvas2"></canvas>


<canvas id="myCanvas3"></canvas>

</body>

Javescript

var c = document.getElementById("myCanvas");
var a = c.toDataURL();
alert(a);

var myCanvas = document.getElementById('myCanvas3');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.src = a;
ctx.drawImage(img, 20, 20);
like image 749
KhongMing Kok Avatar asked Mar 23 '23 10:03

KhongMing Kok


1 Answers

youre missing the onload event of the image:

var image = new Image
image.src = "URL or DataURL"
image.onload = function(){
   ctx.drawImage(image)
}

working fiddle

like image 106
VeXii Avatar answered Apr 02 '23 05:04

VeXii