2
votes

https://jsfiddle.net/awguo/uw1x8m3y/

here is the detailed demo.

I put an img in a div#wrapper and then put a canvas overlap on this img inside that wrapper. I set the width and height of the img and css both to 100%. Then I track the width*height of the canvas. It's not as expected (350x350) but 350x354. Why there is a "4px" more? What should I do to make the canvas size exactly the same as the image (which may also be stretched according to the parent div's width?

Thanks!

$(function() {
  // Why it's 350x354, not 350x350?
  var output = 'canvas size: ' + ($('#overlap').css('width') + ' x ' + $('#overlap').css('height'));
  $('#output').val(output);
});
#wrapper {
  position: relative;
  width: 350px;
}
#wrapper img {
  width: 100%;
}
#overlap {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%
}
#output {
  width: 350px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <img src="http://www.awflasher.com/300x300_demo.png" />
  <canvas id="overlap"></canvas>
</div>

<h3>
    Output:
    </h3>
<input id="output" type="text" />

<p>
  Why the output is 350x354, not 350x350 as expected?
</p>
1

1 Answers

3
votes

Make the image's display inline-block or block. By default it is inline and gets vertical-aligned to baseline, so it gets the crazy 0.5em height extra.

$(function() {
  // Why it's 350x354, not 350x350?
  var output = 'canvas size: ' + ($('#overlap').css('width') + ' x ' + $('#overlap').css('height'));
  $('#output').val(output);
});
#wrapper {
  position: relative;
  width: 350px;
}
#wrapper img {
  width: 100%;
  display: block;
}
#overlap {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
}
#output {
  width: 350px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <img src="http://www.awflasher.com/300x300_demo.png" />
  <canvas id="overlap"></canvas>
</div>

<h3>
  Output:
</h3>
<input id="output" type="text" />

<p>
  Why the output is 350x354, not 350x350 as expected?
</p>

enter image description here