1

我想在画布上绘制多个图像(背景,在背景上另一个图像,然后在该图像上再次出现另一个图像),但有时它会加载图像,有时不会,我使用 setTimeout 来延迟 drawImage 和加载但仍然,它不起作用。

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);
}
4

1 回答 1

2

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

我最近回答了另一个问题。修改后的代码见这里:http: //jsfiddle.net/enhzflep/RLP5Y/

或者这里的问题本身:来自先前功能的图像不在背景中绘制(画布)

于 2012-10-12T05:55:29.730 回答