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

use*_*708 36 html5 canvas

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

如下面的代码段(如果它不会用作替代内容):

<canvas id="imageView" width="100%" height="100%">
    <table>...</table>
</canvas>
Run Code Online (Sandbox Code Playgroud)

Mat*_*ley 35

您可以尝试在画布上设置一个CSS样式position: fixed(或者absolute适当的话),然后跟随它的任何内容(与您在示例中给出的容器内容相对)应该位于它上面.

  • @ fx42:不要设置`z-index:-1`,它与某些浏览器混淆.相反,将其余元素包装在div中并在该div上设置`z-index:1`. (14认同)
  • 刚发现设置z-index:-1; 需要将画布放在其他元素后面. (9认同)
  • 尝试了style ="position:fixed; top:0; left:0",它运行得很好.感谢名单! (8认同)
  • @MatthewScharley:刚刚遇到过这个,但你需要在你设置z-index的div上的位置相对/绝对(http://jsfiddle.net/BlessYAHU/zhZxM/132/). (3认同)

Rob*_*Rob 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>
Run Code Online (Sandbox Code Playgroud)


小智 6

<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>
Run Code Online (Sandbox Code Playgroud)