T
T
TonyStark13372020-03-25 10:32:43
JavaScript
TonyStark1337, 2020-03-25 10:32:43

Why is the image not displayed after overlaying on canvas?

Hi there is a code

var canvas = document.getElementById("myCanvas"), 
                context = canvas.getContext("2d");
                 
            var img = new Image();
      var imgT = new Image();
      
            img.src = "https://img.rosbalt.ru/photobank/1/c/a/0/Z8X2VMCx.jpg";
      imgT.src = "http://zabavnik.club/wp-content/uploads/background_html_1_16082041.jpg"
            img.onload = function() {
                 
                context.drawImage(img, 0, 0);
        context.drawImage(imgT, 300, 400,200,200);
        
            };
      console.log("url-final-  "+canvas.toDataURL());

<canvas id="myCanvas" width="1000" height="1000"
            style="background-color:#eee; border:1px solid #ccc;">
            
        </canvas>


The output in console.log displays everything that is in Canvas in base64 img, when converted to png, a bare photo of 1000x1000 is obtained, but according to the ideas there should be two photos (one on top of the other) why are they not in the final result?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2020-03-25
@TonyStark1337

var canvas = document.getElementById("myCanvas"), 
                context = canvas.getContext("2d");
                 
      var img = new Image();
      var imgT = new Image();
      var loaded = 0;
      img.src = "https://img.rosbalt.ru/photobank/1/c/a/0/Z8X2VMCx.jpg";
      imgT.src = "http://zabavnik.club/wp-content/uploads/background_html_1_16082041.jpg"
      imgT.onload = img.onload = function() {
      	if(++loaded == 2)
        	draw();
      };
      
      function draw(){
        context.drawImage(imgT, 300, 400,200,200);      
        context.drawImage(img, 0, 0);             
           console.log(canvas.toDataURL());

      }

PS Corsa errors and others may fall if the images are not on your host

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question