为什么我必须单击两次按钮才能加载图像?

时间:2020-10-15 02:02:37

标签: javascript css html5-canvas addeventlistener

我是编程新手。我的提交按钮有问题。第一次单击它时,图像不会显示在画布上。下面是我的代码。我已使用onload方法加载图像。我正在使用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);



   
  }
}

1 个答案:

答案 0 :(得分:1)

问题在于图像加载之前您正在使用img.widthimg.height,因此尚不知道尺寸。将这些行放在onload函数中。

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);
    })
  }
}