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

混江龙づ霸主 提交于 2019-12-11 06:05:55

问题


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/



来源:https://stackoverflow.com/questions/6220954/how-do-i-draw-an-image-loaded-from-the-page-in-a-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!