Multiple canvas layers positioning HTML5

2.5k Views Asked by At

I have 2 canvas layers that are positioned on top of each other.

However I need to position them relative to the page.

The width of the layers is 800 and the height 300.

I want to have it center no matter what size screen it is on, and have the height adjust for each size screen also.

Currently I am using:

<div>
    <canvas id="canvas" width="800" height="300"  style="position: absolute; left:20%; top: 40%; z-index: 0;"></canvas>
    <canvas id="canvasAnimation" width="800" height="300"  style="position: absolute; left: 20%; top: 40%; z-index: 0;"></canvas>
</div>

And using lots of <br> to make room for it to be placed.

I am using jQuery also. I know how to get the width of a screen if that helps.

2

There are 2 best solutions below

2
On

You can use the following code and set the width of the container rest all would be set automatically:

<div id="container" style="float:left; width:100px; height:200px;">
   <div style="position:relative; border:1px solid black; width:100%; height:100%">
     <canvas id="canvas" style="position: absolute; left:10%; top: 40%; z-index: 0;border:1px     solid #000000;background-color:red;width:80%; height:30%">CANVAS 1</canvas>
     <canvas id="canvasAnimation" style="position: absolute; left: 5%; top: 40%; z-index: -1;border:1px solid #000000;background-color:green;width:90%; height:30%">CANVAS 2    </canvas>
   </div>
</div>
0
On

The answer Nikhil Doomra gave came close.

If you would just add following style code to the container, it will always center in the page (if the page is wider than the object):

margin-left: auto; 
margin-right: auto;

so the code will then result in this:

<div id="container" style="margin-left: auto; margin-right: auto; width:100px; height:200px;">
  <div style="position:relative; border:1px solid black; width:100%; height:100%">
    <canvas id="canvas" style="position: absolute; left:10%; top: 40%; z-index: 0;border:1px     solid #000000;background-color:red;width:80%; height:30%">
      CANVAS 1
    </canvas>
    <canvas id="canvasAnimation" style="position: absolute; left: 5%; top: 40%; z-index: -1;border:1px solid #000000;background-color:green;width:90%; height:30%">
      CANVAS 2
    </canvas>
  </div>
</div>