开发者

Layering text and images in Canvas HTML5

Hi am making a small HTML5 canvas demo.

I initiated the canvas using modernizer from O'Reilly's HTML5 text.

This is for iPad so my canvas is 1024 by 768.

I then load in a background image in my DrawScreen function.

var backgroundImage = new Image();
backgroundImage.src = "images/background.jpg";
backgroundImage.onload = function(){
    context.drawImage(backgroundImage,0,0);
}

I want to add text to this then. So I do:

function drawText(){
    context.fillStyle ="gray";
    context.font = "28px Helvetica";        
    context.fillText(message, 260, 700);
}

I then call both functions:

    DrawScreen();
  开发者_运维技巧  DrawText();

However my background image totally over writes my text. Or is on top of it. If I disable DrawScreen(); I can see the text. Changing the function order doesn't make a differnce...

How to do this? I feel so stupid that am stuck on something that seems so elementary.

Thanks


The problem is that your image is being drawn after -- and therefore on top of -- your text. This is because of the time it takes the image to load. Basically, what's happening is this:

  • You call your DrawScreen function
  • You start loading your background image by assigning the src attribute
  • You assign the onload() handler to fire once the image has finished loading.
  • DrawScreen exits, having completed all its work
  • You call DrawText, which immediately draws the text
  • At some point later, the image finishes loading, fires the onload() event, and you draw the background image.

I'd suggest restructuring your code so that all the drawing is kicked off by the successful loading of the image. That way, nothing asynchronous will be going on, and the image will be drawn, followed by the text.

Here's a quick example, on jsFiddle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜