【问题标题】:Why do I have to click the button twice to have the image loaded?为什么我必须单击两次按钮才能加载图像?
【发布时间】:2021-01-29 11:33:27
【问题描述】:

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



   
  }
}

【问题讨论】:

  • 你在imageNotFound函数之后多了一个}

标签: javascript css html5-canvas addeventlistener


【解决方案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);
    })
  }
}

【讨论】:

    猜你喜欢
    • 2015-07-02
    • 2021-12-30
    • 2013-01-10
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多