Christian F Christian F - 1 year ago 62
CSS Question

Layering Canvas on another Canvas?

Im currently doing something that goes like:

  • create a canvas and append it to a divider

  • set a background image via CSS on that canvas.

  • draw a hexgrid on the canvas

  • draw PNGs on the canvas.

  • animate those PNGs to display "movement".

However, its a pain having to redraw the entire canvas including the non-moving PNGs.

Im wondering if it would be smarter or better to have a single canvas for the Background/hexgrid and create the PNGs on additional, small canvas elements which are then zIndex'ed on top of the Background canvas. I then could make the animations (PNGs moving) easier.

However, im running into problems in regards to actually placing the "new" canvas's at the right x/y coordinates of the Background canvas.

this.drawShipImage = function(name, id, x, y){

var div = document.getElementById("grid");
// initial, big canvas with background is created elsewhere but has the same width/height than "grid"

var canvas = document.createElement("canvas"); = name + id;
canvas.width = 30;
canvas.height = 30; = "absolute"; = 1;

var context = canvas.getContext("2d");
context.scale(0.75, 0.75);
context.drawImage(ship, 0, 0);


Basicly, this function has 2 important Parameters, that is the x/y Parameter where the new canvas SHOULD be drawn in context to the width/height of the Background canvas.
However im unable to conclude a way to get the Image to appear at the right coordinates.

I suppose the only way it could work is adding = x/y-ish
into the mix ?

Answer Source

Using a second canvas (or just an img element holding your background) might be a good solution since your background will be redrawn less frequently than your animated foreground.

This is particularly true if your device has a GPU because the background element will be cached in the GPU and will redraw very quickly as compared with the relatively slower drawings on your animating foreground canvas.

You can use the CSS position property to stack 2 elements.

  1. Wrap your 2 canvases (or canvas + img elements) in a wrapping div.
  2. Set the wrapper div's position property to relative (meaning children will be positioned relative to the wrapper instead of relative to the page).
  3. Set the 2 canvases (or canvas + img elements) position to 'absolute' (meaning they are subject to being positioned relative to the wrapper).
  4. Set the top & left properties of the child elements to 0 so they will overlap. The default top & left values are zero, so assigning them to zero is optional--but explicitly assigning them to zero is more clear.


<div id='wrapper'>
    <canvas id="canvasBottom" width=300 height=200></canvas>
    <canvas id="canvasTop" width=300 height=200></canvas>


        position:absolute; top:0px; left:0px;
        border:1px solid green;
        border:1px solid red;