Search code examples
javascripthtmldomcanvasz-index

Objects aren't ordering by z-index


If I put into div couple of Canvas objects, they are ordering one bottom other. But not one over other. Only Chrome browser work like as I want.

Where is mistake?

window.onload = function() {
  var div = document.createElement("div")
  div.style = "position: relative; height:100%; width:100%;"
  document.body.appendChild(div)

  var element = document.createElement('canvas');
  element.width = 800;
  element.height = 300;
  element.style = "position: absolute; left: 0; top: 0; z-index: 0;"

  var cvs = element.getContext('2d');
  cvs.fillStyle = 'rgba(200, 200, 200, 155)';
  cvs.fillRect(0, 0, 800, 300);

  div.appendChild(element);

  element = document.createElement('canvas');
  element.width = 800;
  element.height = 300;
  element.style = "position: absolute; left: 0; top: 0; z-index: 1;"

  cvs = element.getContext('2d');
  cvs.fillStyle = 'rgba(0, 255, 0, 155)';
  cvs.fillRect(100, 50, 600, 200);

  div.appendChild(element);
}
<body bgcolor="#ffffff" style="height:100%; overflow:hidden; margin:0;">

  <div id="sample" style="position: relative; height:100%; width:100%;"></div>
</body>

The expected behavior (only by Chrome) enter image description here The observed behavior (IE, Edge, native android browsers) enter image description here


Solution

  • Very strange

    element.setAttribute('style', "position: absolute; left: 0; top: 0; z-index: 1;")
    //element.style="position: absolute; left: 0; top: 0; z-index: 1;"
    

    Thats right