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

2019-08-01 00:00发布

问题:

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

回答1:

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



回答2:

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/