Jerry Ji
Jerry Ji

Reputation: 386

html canvas position woe

I try to overlay a canvas exactly on top of a 256px by 256px image (of 8x8 grids) and draw an 8x8 black square --

    var canvas = document.querySelector("canvas");
    canvas.width = 1024;
    canvas.height = 1024;
    var c = canvas.getContext("2d");
    c.fillRect(0, 0, 8, 8);
    #wrapper {
      margin: 0 auto;
      width: 256px;
    }
    
    #img {
      position: relative;
      top: 0;
      left: 0;
    }
    
    #canvas {
      position: relative;
      margin-top: 0;
      margin-left: 0;
      top: -256px;
      left: 0;
      z-index: 1;
    }
    <html>
      <body>
        <div id="wrapper">
          <img id="img" src="https://i.imgur.com/0qjIa89.png" />
          <canvas id="canvas"></canvas>
        </div>
      </body>
    </html>

However, I don't understand why the black square drawn is slightly offset down relative to the grid image --

enter image description here

complete jsfiddle https://jsfiddle.net/ze8ufqcv/7/

How to position the canvas drawing exactly on top of the image?

Upvotes: 1

Views: 75

Answers (3)

Rocks
Rocks

Reputation: 1155

This issue is due to the img having a vertical-align: baseline which causes 3px space to be added at the bottom. You can remove this by adding vertical align: middle to the img. Since vertical-align doesn't apply to block-level elements, display:block does the job as well.

var canvas = document.querySelector("canvas");
canvas.width = 1024;
canvas.height = 1024;
var c = canvas.getContext("2d");
c.fillRect(0, 0, 8, 8);
#wrapper {
  margin: 0 auto;
  width: 256px;
}

#img {
  position: relative;
  vertical-align: middle;
  /*or display: block*/
  /* not necessary
  top: 0;
  left: 0; */
}

#canvas {
  position: relative;
  margin-top: 0;
  margin-left: 0;
  top: -256px;
  left: 0;
  z-index: 1;
}
<body>
  <div id="wrapper">
    <img id="img" src="https://i.imgur.com/0qjIa89.png" />
    <canvas id="canvas"></canvas>
  </div>
</body>

Upvotes: 2

Ingo86
Ingo86

Reputation: 86

The accepted answer is not shifting the image a few pixels down, but actually eliminating the gap between the initial position of the two elements. You can see this by leaving out the top: -256px; and you'll find a few pixels space in between the image and your canvas. This is eliminated by adding the display:block; .

An alternative would be setting the wrapper to position:relative; and the canvas to position:absolute; and deleting the top offset.

Upvotes: 2

Anzil khaN
Anzil khaN

Reputation: 1984

Add display: block; to your #img selector.

Like this .

#img {
  position: relative;
  top: 0;
  left: 0;
  display: block;
}

Upvotes: 0

Related Questions