简体   繁体   中英

Why do I have to click the button twice to have the image loaded?

I am new to programming. I have an issue with the submit button. The first time I click it the image doesn't show up on the canvas. Below is my code. I have used onload method to load the image. I'm using Chrome.

generateBtn = document.getElementById('button1');
canvas = document.getElementById('meme-canvas');

ctx = canvas.getContext('2d');

canvas.width = canvas.height = 0;

let button1 = document.getElementById('button1');

button1.addEventListener('click', function(e) {
  console.log("clicked", this);

  e.preventDefault();
  let imageurl = document.getElementById('text1').value;

  let img = document.createElement('img');


  img.addEventListener('error', imageNotFound);
  img.crossOrigin = "anonymous";
  img.src = imageurl;


  generateMeme(img, topTextInput.value, bottomTextInput.value);
})

function imageNotFound() {
  alert('That image was not found.');
}
}



function generateMeme(img, topText, bottomText) {


  // Size canvas to image
  canvas.width = img.width;
  canvas.height = img.height;


  // Clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw main image

  img.onload = function() {
    ctx.drawImage(img, 0, 0);



   
  }
}

The problem is that you're using img.width and img.height before the image is loaded, so it doesn't know the dimensions yet. Put those lines inside the onload function.

 function generateMeme(img, topText, bottomText) { img.onload = function() { // Size canvas to image canvas.width = img.width; canvas.height = img.height; // Clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw main image ctx.drawImage(img, 0, 0); let fontSize = canvas.width / 15; ctx.font = fontSize + 'px Impact'; ctx.fillStyle = 'white'; ctx.strokeStyle = 'black'; ctx.lineWidth = fontSize / 15; ctx.textAlign = 'center'; ctx.textBaseline = 'top'; topText.split('\\n').forEach(function(t, i) { ctx.fillText(t, canvas.width / 2, i * fontSize, canvas.width); ctx.strokeText(t, canvas.width / 2, i * fontSize, canvas.width); }) ctx.textBaseline = 'bottom'; bottomText.split('\\n').reverse().forEach(function(t, i) { ctx.fillText(t, canvas.width / 2, canvas.height - i * fontSize, canvas.width); ctx.strokeText(t, canvas.width / 2, canvas.height - i * fontSize, canvas.width); }) } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM