【问题标题】:HTML5 canvas - drawImage not always drawing the imageHTML5 画布 - drawImage 并不总是绘制图像
【发布时间】:2013-03-08 09:58:15
【问题描述】:

每次用户按下按钮时,我都会在画布上绘图,但有时图像不会在画布上绘制。我认为这可能是在 context.drawimage 函数运行之前没有及时加载图像,因为有时会绘制一些较小的文件。我已经使用了控制台并检查了资源,所以这是我能想到的唯一问题。

如何避免这个问题?

这是我的 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);
}

【问题讨论】:

    标签: javascript html5-canvas drawimage


    【解决方案1】:

    您应该检查图像是否已加载。如果没有,则监听 load 事件。

    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,顺便说一句,很好的来源)建议:
    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';
    }
    

    显然,您不想应用描边或填充。但是,想法是一样的。

    【讨论】:

    • 最好在定义 img.onload 处理程序后设置 img.src。
    • 如果您不是从图像而是从 html5 视频控件写入会怎样。当帧在 timeupdate 上发生变化时,无法检查图像是否已加载。
    猜你喜欢
    • 2015-11-01
    • 2013-03-28
    • 2021-03-02
    • 1970-01-01
    • 2013-11-01
    • 2016-08-22
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多