开发者

How do I draw an image loaded from the page in a canvas

开发者 https://www.devze.com 2023-03-09 22:26 出处:网络
I have a html page like this: <html> <body> (1)<canvas id=\"cs\"></canvas> (2)<img src=\"/image.png\" id=\"img\"/>开发者_开发百科

I have a html page like this:

<html> 
    <body>
          (1)<canvas id="cs"></canvas>
          (2)<img src="/image.png" id="img"/>开发者_开发百科 
    </body> 
</html>

I would like to know how I could load and display the image (2) in the canvas (1) (with drawImage function). I tried this but it doesn't work :

var img = $("#img");
ctx.drawImage(img,0,0);


You have to ensure that your image has loaded first. Try wrapping your drawImage call in a ready statment and make certain you are setting up your canvas object first.

$().ready(function(){
   var canvas = document.getElementById('canvas');
   var ctx = canvas.getContext('2d');
   ctx.drawImage(document.getElementById("img"),0,0);

})

If you haven't already found it here is a nice tutorial: https://developer.mozilla.org/en/Canvas_tutorial/Using_images


Is that all of your code?

You need to set up the canvas first:

var ctx = document.getElementById('cs').getContext('2d');
var img = new Image();
img.src=document.getElementById('img').src;
ctx.drawImage(img,0,0);

Something like that...

Here's an example in jsfiddle: http://jsfiddle.net/vTYqS/

Note that the first picture gets cut off because of the default canvas size. Depending on the image you plan to copy, you may need to resize your canvas like this:

http://jsfiddle.net/vTYqS/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消