Javascript 为什么我必须点击两次按钮才能加载图像?
我是编程新手。我对提交按钮有问题。我第一次单击它时,图像不会显示在画布上。下面是我的代码。我使用了onload方法来加载图像。我用的是ChromeJavascript 为什么我必须点击两次按钮才能加载图像?,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
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
函数之后,您有一个额外的}
。