Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我必须点击两次按钮才能加载图像?_Javascript_Css_Html5 Canvas_Addeventlistener - Fatal编程技术网

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

Javascript 为什么我必须点击两次按钮才能加载图像?,javascript,css,html5-canvas,addeventlistener,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 butto

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



   
  }
}

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

function generateMe(img、topText、bottomText){
img.onload=函数(){
//根据图像调整画布大小
canvas.width=img.width;
canvas.height=img.height;
//透明帆布
clearRect(0,0,canvas.width,canvas.height);
//绘制主图像
ctx.drawImage(img,0,0);
让fontSize=canvas.width/15;
ctx.font=fontSize+“px影响”;
ctx.fillStyle='白色';
ctx.strokeStyle=‘黑色’;
ctx.lineWidth=fontSize/15;
ctx.textAlign='中心';
ctx.textb基线='top';
topText.split('\n').forEach(函数(t,i){
ctx.fillText(t,canvas.width/2,i*fontSize,canvas.width);
ctx.strokeText(t,canvas.width/2,i*fontSize,canvas.width);
})
ctx.textb基线='底部';
bottomText.split('\n').reverse().forEach(函数(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);
})
}

}
imageNotFound
函数之后,您有一个额外的
}