Shivam Shivam - 5 months ago 22
Javascript Question

canvas element unable to draw image

I wrote a few lines of code to draw an image but seems like it keeps on loading, I tried some W3 School code using the basic implementation but that works fine.

What is happening here is it looks like its stuck in some invisible loop and unable to draw an image.

<script>
var canvas=null;
var context=null;
setup=function(){
canvas=document.getElementById("my_canvas");
context=canvas.getContext('2d');
canvas.width=1200;
canvas.height=720;
img=new Image();
img.onload=onImageLoad;
img.src="http://imgge.bg.ac.rs/images/logo1.jpg";
context.drawImage(img,192,192);
};
onImageLoad=function(){
document.write("done !!");
context.drawImage(img,155,10);
};
setup();
</script>

Answer

I replaced your document.write() with a console.log() and it works fine:

var canvas = null;
var context = null;

var setup = function() {
  canvas = document.getElementById("my_canvas");
  context = canvas.getContext('2d');
  canvas.width = 1200;
  canvas.height = 720;
  img = new Image();
  img.onload = onImageLoad;
  img.src = "http://imgge.bg.ac.rs/images/logo1.jpg";
  context.drawImage(img, 192, 192);
};

onImageLoad = function() {
  console.log("done !!");
  context.drawImage(img, 155, 10);
};

setup();
<canvas id="my_canvas"></canvas>

For the reason why document.write() causes the canvas to not be displayed, read document.write() overwriting the document?

You might notice a difference between the first and consecutive runs due to img being cached by your browser. A cached image is immediately available for drawing within the setup() function.

Comments