我页面背景中的html5画布元素?

时间:2010-04-27 08:15:55

标签: html5 canvas

是否可以在网页的背景中使用全屏画布元素,并在其前面使用“普通”标记元素?

类似于以下代码段(如果它不会用作替代内容):

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

4 个答案:

答案 0 :(得分:32)

您可以尝试在画布上设置一个CSS样式,其中position: fixed(或absolute视情况而定),然后跟随的任何内容(相反)你在例子中给出的容器内容应该放在它上面。

答案 1 :(得分:7)

我使用以下代码为您尝试了。正如马修描述的那样,div被放置在canvas元素的顶部。所以应该为你工作

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

答案 2 :(得分:5)

<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>

答案 3 :(得分:0)

您可以使用toDataURL()将其放在与HTML分离的纯JS中

var c = document.createElement('canvas'),        
    ctx = c.getContext('2d'),
    size = c.width = c.height = 50;

for( var x = 0; x < size; x++ ){
    for( var y = 0; y < size; y++ ){
        ctx.fillStyle = 'hsl(0, 0%, ' + ( 100 - ( Math.random() * 15 ) ) + '%)';
        ctx.fillRect(x, y, 1, 1);
    }
}

document.body.style.background = 'url(' + c.toDataURL() + ')';
HTML on <b>canvas background</b>

基于此CodePen

相关问题