0

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>
theblindprophet
  • 7,767
  • 5
  • 37
  • 55
Shivam
  • 383
  • 1
  • 3
  • 8

2 Answers2

0

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.

Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74
0

First you don't need to write context.drawImage(img,192,192); two times only write inside the image.onload() function. when you write anything using using document.write("Done !"); , it will write the content on this document(HTML) page and may create problems. Instead of that write message on <p> tag instead of on whole document.

here is a snippet for your code:

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(){        
        context.drawImage(img,155,10);
      document.getElementById("report").innerHTML="Done !";
    };
setup();
<canvas id="my_canvas"></canvas>
<p id="report"></p>