Why is the base64 from toDataURL blank?

problem description

Why is the base64 from toDataURL blank?

the environmental background of the problems and what methods you have tried

more known coordinate points, generate pictures, and transfer to base64

related codes

/ / Please paste the code text below (do not replace the code with pictures)
var area = {

  "ship"  : {"x":10,"y":10,"w":100,"h":25},
  "order"  : {"x":15,"y":40,"w":110,"h":35},
  "port"  : {"x":90,"y":100,"w":180,"h":55}      

}

var base = get_base64 ("1212121.jpgcircle area);

for (var i in base) {

var img = "<img src=""+base[i]+"">";
$("body").append(img);

}

function get_base64 (url,area) {

 base=[];
  for(var i in area){
    var base64 = canvas_to_base64(area[i].x,area[i].y,area[i].w,area[i].h,url);
    base.push(base64);
  }
  return base;

}
function canvas_to_base64 (ax,ay,aw,ah,url) {

  var imgCanvas = $("<canvas id="cava">")[0];
      imgCanvas.width = aw;
      imgCanvas.height = ah;
  var imgContext = imgCanvas.getContext("2d");
  var img = new Image(); 
  img.src = url;
  img.addEventListener("load",imgeve,false)
  function imgeve(){
    drawScreen();
  }
  function drawScreen(){
    imgContext.drawImage(img, 0, 0);
    imgContext.drawImage(img,ax,ay,aw,ah,0,0,aw,ah);
  }
  // body
  $("body").append(imgCanvas);
  // base64  
  console.log(imgCanvas.toDataURL("image/jpg"));
  return imgCanvas.toDataURL("image/jpg");

}
/ / the problem is transparent, only the canvas? The picture wasn"t inserted into the canvas? The picture hasn"t been loaded yet, and the canvas has been cut off.

what result do you expect? What is the error message actually seen?

Apr.10,2021

as you might guess, the canvas has been cut off before the picture has been loaded.

imgCanvas.toDataURL ('image/jpg') is executed before the drawScreen function runs, so you can't get the data. It can be displayed in body because it is a drawScreen function that waits for the image to finish loading.


did the boss solve the problem? I'm in the same situation

.
Menu