HTML5 Canvas & z-index issue in Google Chrome

2019-05-07 22:56发布

I have found that applying a z-index to a canvas that has position:fixed causes Chrome to stop rendering all other elements which have position:fixed properly. However, this only happens if the canvas is greater than 256x256px in size.

Here's an example:

<!DOCTYPE html>
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <style>
    h1     { position: fixed; }
    body   { height: 2000px; }
    canvas { position: fixed; z-index: -10; }
  </style>
</head>
<body>
  <h1>Test Title</h1>
  <canvas id="backgroundCanvas" width="956" height="256"></canvas>
  <script>
  // draw basic shape
  (function() {
    var c = document.getElementById("backgroundCanvas");
    var ctx = c.getContext("2d");

    ctx.beginPath();
    ctx.moveTo(0,100);
    ctx.lineTo(0,0);
    ctx.lineTo(100,0);
    ctx.lineTo(1000,1000);
    ctx.fillStyle = "rgb(117, 164, 68)";
    ctx.fill();
    ctx.closePath();
  })();
  </script>
</body>
</html>

If you paste this into a html document and open it in Chrome, you should see what I mean.

My question is, does anyone know of a way I can get around this issue?

4条回答
淡お忘
2楼-- · 2019-05-07 23:26
* {
z-index: inherit;
}

works for me.

查看更多
不美不萌又怎样
3楼-- · 2019-05-07 23:31

I had the same problem with negative z-indexes, and a simple fix if you can allow for it is to set the html elements overflow-y to auto.

html{
    overflow-y: auto;
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-05-07 23:36

I had that problem in Chrome on Win8, and making canvas and siblings position:fixed did't help me. I found that i had negative z-index on canvas DIV. When I rearrange my code and make that z-index positive, canvas stopped flickering my overlay DIVs

查看更多
孤傲高冷的网名
5楼-- · 2019-05-07 23:45

I tested the same fiddle in Chrome 27/winXP and it behaves exactly as you describe; It looks like a bug in chrome or webkit for windows, I tested early with chrome 23/linux and it worked OK.

I found a workarround jsfiddle by warping both, the h1 and the canvas with a fixed div:

<div id='fixedContainter'>
    <h1>Test Title</h1>
    <canvas id="backgroundCanvas" width="956" height="256"></canvas>
</div>

The div should also have z-index:-10 if your intent is to make it a background.

CSS:

#fixedContainter{position: fixed; z-index: -10; }
h1{position: fixed;}
body{height: 2000px; }
canvas{ position: fixed; z-index: -10; }

查看更多
登录 后发表回答