html - 为什么这段代码中的 Canvas 大小与预期不符?

标签 html css canvas

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

这是详细的演示。

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

谢谢!

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

最佳答案

使图像的显示成为inline-blockblock。默认情况下,它是内联,并且将vertical-align编辑到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>

enter image description here

关于html - 为什么这段代码中的 Canvas 大小与预期不符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39873890/

相关文章:

javascript - 内容可编辑的字数,包括默认文本

html - 调整父 block Accordion 的大小以调整子 block 的大小

javascript - 如何使用 html javascript 在 Canvas 上绘制点

c# - 将嵌套列表绑定(bind)到 WPF Canvas 面板

html - 如何水平居中绝对div的内容

html - 自定义复选框不适用于多个复选框

javascript - 文本对齐 : right; keep a margin no matter what I try

javascript - context.fillText 的变量

html - 使用图像的响应式菜单

html - 使用 css 伪选择器的正确方法?