tags:

views:

1407

answers:

3

Is it possible to have a full screen canvas element in the background of a webpage and "normal" markup elements like a table in front of it?

like the following snippet (if it wouldn't be used as alternative content):

<canvas id=&#34;imageView&#34; width=100%; height=100%;>
<table>...</table>
</canvas>

+1  A: 

You could try setting a CSS style on the canvas where it has a position: fixed (or absolute as appropriate), and then any content that follows it (as opposed to container content as you've given in your example) should sit on top of it.

Matthew Scharley
tried style="position:fixed; top:0;left:0" and it works just fine. thanx!
just discovered that setting z-index:-1; is needed to put the canvas behind the other elements.
@fx42: Don't set `z-index: -1`, it messes with some browsers. Rather, wrap the rest of your elements in a div and set `z-index: 1` on that div.
Matthew Scharley
+1  A: 

I tried it for you with the following code. The div gets placed on top of the canvas element just as Matthew describes it. So should work for you

<!DOCTYPE HTML>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Canvas demo</title>
<style type="text/css">
    #canvasSection{ position:fixed;}
</style>
<script type="text/javascript">
function draw()
{

//paint the text
var canvas = document.getElementById('canvasSection');
var context = canvas.getContext('2d');

context.fillStyle    = '#00f';
context.font         = 'italic 30px sans-serif';
context.textBaseline = 'top';
context.font         = 'bold 30px sans-serif';
context.strokeText('Your Text!!', 0, 0);

//paint the square

var canvasSquare = document.getElementById('canvasSquare');
var ctxSquare = canvas.getContext('2d');

ctxSquare.fillStyle='#FF0000';
ctxSquare.fillRect(0, 100,50,100);
}
</script>
</head>
<body onLoad="draw()">
<canvas id="canvasSection">Error, canvas is not supported</canvas>
<div>TestText</div>
</body>
</html>
Rob
+1  A: 

You can't yet do this in normal HTML5 without hacky positioning stuff, but Webkit-based browsers do allow you to use a element in the CSS background property. Just give the canvas an id, then use body { background:url(#mycanvas); } in your CSS.

Xanthir
Positioning isn't "hacky", this is exactly what it was designed for...
Matthew Scharley
Positioning isn't designed for use in creating backgrounds for things. That's why it's hacky. The `background` property exists for a reason.
Xanthir