mohaidar
mohaidar

Reputation: 4251

drawImage canvas method is running before the 'img' element has had a chance to fully load

drawImage canvas method is running before the 'img' element has had a chance to fully load so I need your help o fix this problem.

<canvas id="drawImage" width="900" height="900" style="">  </canvas>
<img id="img" src="images/fb.png"/>

<script type="text/javascript">

    var canvas  = document.getElementById("drawImage");
    var cont = canvas.getContext("2d");
    var img = document.getElementById("img");
    cont.drawImage(img , 100 , 100);

</script>

I tried this code to draw image , but it does not draw any thing

Upvotes: 1

Views: 660

Answers (2)

markE
markE

Reputation: 105015

First, your code to draw the 'img' element into canvas is correct.

One problem is that that code is running before the 'img' element has had a chance to fully load.

Therefore, you must tell the browser not to run your javascript until the page elements are fully loaded.

You can tell the browser by wrapping your javascript in window.onload like this:

<script>
window.onload=(function(){

    var canvas  = document.getElementById("drawImage");
    var cont = canvas.getContext("2d");
    var img = document.getElementById("img");
    cont.drawImage(img , 100 , 100);

}); // end $(function(){});
</script>

Note: Html Canvas is designed to be able to read the pixels in an img-element. Canvas cannot do the same with other canvas elements (you mention a div in your question). There is a plugin script that translates html into canvas drawings: http://html2canvas.hertzen.com/

Upvotes: 0

desu
desu

Reputation: 455

As I know, you couldn't put any DOM elements in canvas. But you can try putting image in canvas like that

var example = document.getElementById("example"),
ctx = example.getContext('2d'), // context
pic = new Image();              // creating new image
pic.src = 'http://habrahabr.ru/i/nocopypast.png'; //source
pic.onload = function() { // Waiting till load
    ctx.drawImage(pic, 0, 0);
} // Draw image when it's loaded

Upvotes: 4

Related Questions