canvas.drawImage没有绘制所有图像

时间:2012-10-12 05:04:27

标签: javascript jquery canvas html5-canvas

我想在画布上绘制多个图像(背景,在背景上另一个图像, 并在那个图像上再次出现另一张图片),  但有时它加载图像,有时不加载图像, 我使用setTimeout来延迟绘制图像和加载,但仍然无法正常工作。

if(somecondition)
{
    //background image is 70kb
    //image on background is 65kb

    img3.src = "Image  path"; //images is almost 2kb 
    img4.src = "Image  path"; //images is almost 2kb 
    img5.src = "Image  path"; //images is almost 2kb 
    img6.src = "Image  path"; //images is almost 2kb 
    setTimeout(function()
    {
        img3.onload = function() 
        {
          context.drawImage(img3, 272, 139, 172, 31);
        }
    },1000);
    console.log("Linesss2 > 4 "+lines2);
    bottomY = 290+((lines1-5)*10);
    middleHeight = bottomY - 170;




    setTimeout(function()
    {
        img4.onload = function() 
        {
          context.drawImage(img4, 272, 170, 172, middleHeight);  ///272
        }
        img6.onload = function() 
        {
          context.drawImage(img6, 272, bottomY, 172, 71);
        }
    },1000);

    }
    var metrics1 = context.measureText(canvasText1);
    var testWidth1 = metrics1.width;

    var metrics2 = context.measureText(canvasText2);
    var testWidth2 = metrics2.width;

    context.fillText(canvasText1, 169.5-(testWidth/2), y-20);
    context.fillText(canvasText2, 169.5-(testWidth/2), y-20);
    wrapTextForCanvas1(context, canvasText1, 50, 180);
    wrapTextForCanvas2(context, canvasText2, 260, 180);
}

1 个答案:

答案 0 :(得分:2)

因此,您不希望运行任意超时,您希望在每个图像加载时收到通知。这样你就可以确定在你开始尝试使用它们之前它们已经全部加载了。只需设置每个图像的onload回调,使其递增计数器。当该计数器达到您必须加载的图像数量时,它们都已完成,您可以开始使用它们。

我最近回答了另一个问题。请参阅此处了解修改后的代码: http://jsfiddle.net/enhzflep/RLP5Y/

或者问题本身:Images from previous functions are not drawn in the background (Canvas)