【问题标题】:Why the canvas size in this code is not as expected?为什么此代码中的画布大小不符合预期?
【发布时间】:2016-10-05 12:24:22
【问题描述】:

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

这里是详细的演示。

我在 div#wrapper 中放置了一个 img,然后在该包装器内的该 img 上放置了一个画布重叠。我将 img 和 css 的宽度和高度都设置为 100%。然后我跟踪画布的宽度*高度。它不是预期的 (350x350) 而是 350x354。为什么多了一个“4px”?怎么做才能让canvas大小和图片完全一样(也可以根据父div的宽度进行拉伸?

谢谢!

$(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>

【问题讨论】:

    标签: html css canvas


    【解决方案1】:

    使图像显示为inline-blockblock。默认情况下它是inline 并得到vertical-aligned 到baseline,所以它得到了疯狂的0.5em 高度。

    $(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>

    【讨论】:

    • 天啊,这个答案太快了。谢谢各位,我去试试!
    • 我猜你的意思是inlinebaseline 不是display 的有效值
    • @Kaiido 我的意思是vertical-align 值。很抱歉造成混乱。
    • 相当混乱是的。然后不需要显示块,只需在img上设置vertical-align:top也可以。
    • @Kaiido True... 那是另一种方式。
    猜你喜欢
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2022-10-01
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多