-2

I got this sample of code which i was working on it, i got a trouble with because my image angular doesn't appear on the web browser, i can't understand what's my mistake, thanks in advance for your help.

<html>

<script>

var canvas,context;

function init(){


canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
monImg = new Image();
monImg.src="img/angular.png";
context.drawImage(monImg,300,300);


}


window.onload=init();


</script>

 <body>
  <canvas id="canvas" width="1920" height="1080"></canvas>
 </body>
Clément
  • 33
  • 1
  • 7
  • Is `img/angular.png` found and loaded in the browser's network tab? – Jeremy Thille Jan 09 '19 at 13:50
  • 1
    ` – Grynets Jan 09 '19 at 13:51
  • Yes the img/angular.png is found by the web browser – Clément Jan 09 '19 at 13:51
  • Yes i tried to move the script it doesn't change anything unfortunately – Clément Jan 09 '19 at 13:53
  • There’s no way that works as written, since `window.onload = init()` just calls `init` right away. `canvas` won’t exist yet and `canvas.getContext('2d')` will throw an error without getting to the image part. Please show your full HTML in the right order. – Ry- Jan 09 '19 at 13:53
  • The canvas element cannot be found because the script is looking for it in the DOM before it's actually there. – iCode Jan 09 '19 at 13:55
  • Possible duplicate of [Waiting for image to load in Javascript](https://stackoverflow.com/questions/2342132/waiting-for-image-to-load-in-javascript) – kemicofa ghost Jan 09 '19 at 13:56
  • No it's another question because the onload doesn't solve the problem – Clément Jan 09 '19 at 13:59

2 Answers2

2

See this question.

You have to wait for the image to load before you do anything with it. The easiest way is:

monImg = new Image();
monImg.onLoad = function() {
    context.drawImage(monImg, 300, 300);
}
monImg.src = "img/angular.png";
Calvin Godfrey
  • 2,171
  • 1
  • 11
  • 27
1

You need to add a handler for the Image onload where you call drawImage() such as:

 <html>

 <body>
  <canvas id="canvas" width="1920" height="1080"></canvas>
 </body>

<script>

var canvas,context;

function init(){

canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
monImg = new Image();
monImg.src="img/angular.png";
monImg.onload = function() {
    context.drawImage(monImg,300,300);
}

}


window.onload=init();


</script>

 </html>
iCode
  • 1,254
  • 1
  • 13
  • 16