简体   繁体   中英

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);

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

The first canvas is empty and that's why nothing gets drawn on the third one. Do this first.

var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.src = "http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG";
ctx.drawImage(img, 20, 20);

You have to draw an image on a canvas. Just be having an img tag before the canvas tag will not draw the image on your canvas element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM