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-block
或block
。默认情况下,它是内联
,并且将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>
关于html - 为什么这段代码中的 Canvas 大小与预期不符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39873890/