Displaying a <div> over a <canvas>
Solution 1
This can only be fixed by applying the style:
#d {position:relative;}
or
#d {position:absolute;}
Solution 2
This occurred to me recently and instead of changing how it's laid out, I switched from div
to using a span
with display:inline-block
.
Works on Firefox/Chrome/Safari. Have not tested in IE.
Solution 3
Use the following code, hope it helps you:
<head>
<style type="text/css">
#c{background-color:#000;z-index:-1;position: fixed;}
#d{background-color:#aa00aa;margin-top:-50px;z-index:0;}
</style>
<script type="text/javascript">
function load() {
var cntx = document.getElementById("c").getContext("2d");
cntx.fillStyle = "rgba(255, 200, 200, 1)";
cntx.canvas.top = "0";
cntx.canvas.left = "0";
cntx.fillRect(0, 0, cntx.canvas.width, cntx.canvas.height);
var obj = document.getElementById("d");
obj.style.position = "fixed";
obj.style.top = 50;
obj.style.left = 0;
}
</script>
</head>
<body onload="load()">
<canvas id="c" width="500" height="300"></canvas>
<div id="d" style="width:500px;height:300px"></div>
</body>
Moncader
Updated on July 10, 2022Comments
-
Moncader almost 2 years
The problem, which exists in both Firefox and Chrome, is that I have a canvas with a solid background, and a div with a solid background color/image. The div is margined up over top of the canvas. The div does not display over the canvas. An interesting note is that if there is text inside the div it will properly get displayed. This would mean it's a browser bug... in both browsers. Here is some code for people that want to try it.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type="text/css"> #d{background-color:#111;margin-top:-150px;z-index:999999;} </style> <script type="text/javascript"> function load() { var c = document.getElementById("c").getContext("2d"); c.fillStyle = "rgba(255, 200, 200, 1)"; c.fillRect(0, 0, c.canvas.width, c.canvas.height); } </script> </head> <body onload="load()"> <canvas id="c" width="500" height="300"></canvas> <div id="d" style="width:500px;height:300px"></div> </body> </html>
So, anybody have any workarounds? Or is there something that I missed in the HTML5 spec that says this is correct?
As a note, please do not ask why I want to use margins instead of fixed/absolute/etc... alternatives. I need margins.
-
Moncader over 13 yearsPlease read the question before answering. I said I don't want absolute or relative positioning.
-
Moncader over 13 yearsPlease read the question before answering. I said I don't want absolute or relative positioning.
-
Moses over 13 yearsThat's unfortunate, because absolute and relative positioning are really the only options you have.
-
webdesserts over 12 yearsYou don't actually have to position the elements with relative positioning, you just have to add the property. The position of your div will not change as long as you don't add a
top
,right
, etc... attribute.