简体   繁体   中英

HTML Canvas Layering Frameworks

I'm building an app using the HTML 5 canvas tag, and so far it works great. The next step for the app is layering, so that I have a background image and them some more layers on top of that. Right now I'm doing this:

this.drawMarkers = function(markers) {
    selectedImage = null;
    map.width = map.width;
    for(var i in markers) {
        for(var j in markers[i]) {
            var holder = markers[i][j];
            if(holder !== null) {
                var marker = new Marker(new Cell(holder.row, holder.column), holder.type);
                marker.src = holder.src;
                marker.draw();
            }
        }
    }
    initGrid();
}

where i is the layer and j is the things on that layer. The initial code for this just drew everything on one layer and it worked great, and this one does too if everything downloads in the correct order. If not, things get stacked incorrectly. For example, if the background is large and ends up downloading last, it ends up clearing out everything on top of it due to everything being asynchronous.

Are there any frameworks out there for adding layering to canvas to avoid this? I'm fine if things don't load in the correct order, so long as the stacking is preserved.

First question to ask yourself:

If you draw it repeatedly, say every 100 milliseconds, does the problem go away?

If no, the "drawing in the wrong order" is something you are doing and not an async error. I suspect this might be the case.

Images may not draw, but nothing should draw in the wrong order , assuming your draw routine is correct and that you are redrawing everything each time. According to the canvas spec, a call to drawImage does nothing if the image isn't loaded, so incorrect stacking should be impossible unless it is the order of your own calls.

In any case, you should wait until all of the images you are going to use have loaded before you draw. Use their onload events and/or $(window).load() or jQuery(document).ready , etc.

Some other notes:

  • Depending on how interactive your canvas is and how the layers work, sometimes it is better to use multiple canvases stacked on top of each other to increase performance, especially if a top layer changes very little and a layer underneath changes often.
  • If your background is a static file such as a png, set the CSS background-image of the canvas to that image to make the drawing easier on yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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