HTML5 Canvas & z-index issue in Google Chrome

╄→尐↘猪︶ㄣ 提交于 2019-12-22 09:07:41

问题


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?


回答1:


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




回答2:


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




回答3:


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:


* {
z-index: inherit;
}

works for me.



来源:https://stackoverflow.com/questions/13857518/html5-canvas-z-index-issue-in-google-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!