2010-04-27 63 views
27

是否有可能在網頁的背景中有一個全屏幕的畫布元素,並在它前面有一個「正常」的標記元素?我的頁面背景中的html5 canvas元素?

像下面的代碼片段(如果它不會被用來作爲替代內容):

<canvas id="imageView" width="100%" height="100%"> 
    <table>...</table> 
</canvas> 

回答

29

你可以嘗試在那裏它在畫布上設置一個CSS樣式position: fixed(或absolute如適用),然後遵循的任何內容(與您在示例中給出的容器內容相反)應該位於其上。

+5

嘗試風格= 「的位置是:固定;頂部:0;左:0」,它工作得很好。感謝名單! – user306708 2010-04-27 08:42:45

+7

剛剛發現設置z-index:-1;需要將畫布放在其他元素的後面。 – user306708 2010-04-27 09:46:24

+13

@ fx42:不要設置'z-index:-1',它會在某些瀏覽器中混亂。相反,將其餘元素包裝在div中並在該div上設置「z-index:1」。 – 2010-04-27 11:03:02

6

我用下面的代碼爲你試了一下。 div被放置在canvas元素的頂部,就像Matthew描述的一樣。因此,應該爲你工作

<!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> 
+0

謝謝你的代碼示例。 – mihsathe 2013-01-03 23:34:39

4
<html> 

    <style> 
    body{ 
     margin:0; 
     padding:0; 
    } 
    canvas{ 
     position:absolute; 
     left:0; 
     top:0; 
     z-index:-1; 
    } 
    div{ 
     position:absolute; 
     z-index:0; 
     left:12px; 
     top:10px; 
    } 
    </style> 
    <body> 

    <canvas id="myCanvas" width="600" height="600" style="border:1px solid #c3c3c3;"> 
     Your browser does not support the canvas element. 
    </canvas> 
    <div>hello is floating div</div> 

    <script type="text/javascript"> 
     var c=document.getElementById("myCanvas"); 
     var ctx=c.getContext("2d"); 
     var grd=ctx.createLinearGradient(0,0,600,600); 
     grd.addColorStop(0,"#FF0000"); 
     grd.addColorStop(1,"#00FF00"); 
     ctx.fillStyle=grd; 
     ctx.fillRect(0,0,600,600); 
    </script> 

    </body> 
</html> 
+1

Firstyl你需要js進行畫布繪製。 但是你可以通過使用CSS來獲得背景作爲背景。試試這個腳本。並可能爲你的需要:) – 2012-05-30 04:19:27