简体   繁体   English

HTML5 画布 - drawImage 并不总是绘制图像

[英]HTML5 canvas - drawImage not always drawing the image

I am drawing on the canvas each time a user presses a button, however sometimes the image is not getting drawn on the canvas.每次用户按下按钮时,我都会在画布上绘图,但有时图像没有绘制在画布上。 I think this could be that the image isn't loaded in time before the context.drawimage function runs, as some of the smaller files sometimes get drawn.我认为这可能是在 context.drawimage 函数运行之前没有及时加载图像,因为有时会绘制一些较小的文件。 I've used the console and checked resources and so this is the only problem I can think of.我已经使用了控制台并检查了资源,所以这是我能想到的唯一问题。

How do I avoid this problem?我如何避免这个问题?

This is my Javascript code.这是我的 Javascript 代码。

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var questionbg = new Image();
var answerbg = new Image();

//this code is inside a function that is called each time a user presses a button
if(questiontype == "text"){
    questionbg.src = "./resources/textquestionbg.png";
    context.drawImage(questionbg, 0, 0);
    }
//if image question
else if(questiontype == "image"){
questionbg.src = "./resources/imageaudiovideoquestionbg.png";
context.drawImage(questionbg, 0, 0);
}
//if audio question
else if(questiontype == "audio"){
questionbg.src = "./resources/imageaudiovideoquestionbg.png";
context.drawImage(questionbg, 0, 0);
}
//else it is a video question
else{
questionbg.src = "./resources/imageaudiovideoquestionbg.png";
context.drawImage(questionbg, 0, 0);
}

You should check if the image is loaded.您应该检查图像是否已加载。 If not then listen to the load event.如果没有,则侦听加载事件。

questionbg.src = "./resources/imageaudiovideoquestionbg.png";
if (questionbg.complete) {
    context.drawImage(questionbg, 0, 0);
} else {
    questionbg.onload = function () {
        context.drawImage(questionbg, 0, 0);    
    };
}


MDN (Mozilla Doc, great source btw) suggests: MDN (Mozilla Doc,很棒的来源顺便说一句)建议:

 function draw() { var ctx = document.getElementById('canvas').getContext('2d'); var img = new Image(); img.onload = function(){ ctx.drawImage(img,0,0); ctx.beginPath(); ctx.moveTo(30,96); ctx.lineTo(70,66); ctx.lineTo(103,76); ctx.lineTo(170,15); ctx.stroke(); }; img.src = '/files/4531/backdrop.png'; }

Obviously, you are not wanting to apply the stroke or fill.显然,您不想应用描边或填充。 However, the idea is the same.然而,想法是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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