In html 5, how to position a div element on top of a canvas element?

Can someone help me: I'm trying to put a div element (say 10px by 10px) on top (in front) of the canvas element (say 500px by 500px) in html. I tried to change each z-index, but to no avail. Does anyone have any ideas, or is this one of those things you really can't do? I already know how to do absolute positioning and that's it, the div element just hangs in the background behind the canvas element. I need a way to bring it to the front and canvas element on the back.

Thanks!

+6
css html5
source share
6 answers

The way absolute positioning works is that, in general, elements that were previously in the code lag behind elements that are later in the code. To change this, you really use z-index. Note, however, that the z-index only works with located elements.

Another thing that can turn you off is that all positioned items act as z-index β€œcontainers”. Therefore, if your <div> appears earlier in the document and in another positioned container, it can be attached to the z-index layer of its ancestor and therefore cannot escape and appear on top of <canvas> . If so, you will either have to rewrite your CSS a bit, or reorder your page so that the <div> in a good place.

+12
source share

It depends on where your items are.

To use z-index, you must set the position to both relative and absolute.

+2
source share

I don't seem to have the same problem. I created the canvas / div sample that you are talking about here in JSbin: http://jsbin.com/adowo/edit

Is this what you are looking for? Or am I missing something?

+1
source share

Sometimes this can happen in my experience. I do not know what is happening in the html5 canvas API. If you want to draw a shape under the div element, use the img tag below.

--- This code example is written with prototype.js (1.6) ---

<-javascript code β†’

 var canvas = $('canvas'); canvas.width = 200; canvas.height = 200; var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(100, 100, 100, 0, - 360 * Math.PI / 180, true); ctx.fillStyle = 'rgba(204, 204, 255, 1)'; ctx.strokeStyle = 'rgba(0, 51, 153, 1)'; ctx.fill(); ctx.stroke(); var imgStr = canvas.toDataURL(); var element = new Element('img', {'src' : imgStr); var target = $('layer1'); target.insert(element); 

<- html β†’

 <div id='layer2' style='z-index : 50;'>&nbsp;</div> <canvas id='canvas' style='z-index : 30;'></canvas> <div id='layer1' style='z-index : 10;'></div> 

By the way, my homepage is written in Japanese.

+1
source share

I worked with this for a while and finally got it to work after setting the z-index of what I want in the background, -1 (compared to some positive number).

0
source share

XHTML

 <div id="canvas"> <div id="topelement"> </div> </div> 

Css styling

 #canvas { height: 500px; width: 500px; overflow: hidden; } #topelement { height: 10px; width: 10px; float: left; } 
-7
source share

All Articles