我似乎无法在 IE9 的固定容器中缩放由图像填充的 Canvas 。有人知道解决方法吗?我记得读过一些关于 IE 如何将 Canvas 视为 block 元素的其他帖子
<style type="text/css">
#container { max-width: 25%; max-height: 25%; }
canvas { max-width: 90%; max-height: 90%; }
</style>
<script type="text/javascript">
var img = new Image();
img.src = 'http://l.yimg.com/dh/ap/default/121214/babydeer340.jpg';
img.onload = function () {
$('canvas').each(function () {
var ctx = this.getContext("2d");
ctx.drawImage(img, 0, 0);
});
};
</script>
<div id="container">
<canvas id='fit-to-specified-width-height-with-aspect-ratio'></canvas>
</div>
<canvas id='normal'></canvas>
最佳答案
我也希望这种行为在所有浏览器中都是一致的,但看起来 IE9 和其他一些浏览器将 Canvas 视为 block 级元素,因此您需要同时设置宽度和高度的样式。
canvas 元素在其大小上必须依赖硬像素,因为它是光栅化的。一种方法是根据图像的原始大小和所需的比例来计算和设置这些像素。
我 fork 了你的 JSFiddle:http://jsfiddle.net/cbosco/ttU5L/3/
var img = new Image();
var SCALE = 0.25;
img.onload = function () {
$('canvas').each(function () {
var w = img.width;
var h = img.height;
w *= SCALE;
h *= SCALE;
this.width = w;
this.height = h;
var ctx = this.getContext("2d");
ctx.scale(SCALE, SCALE);
ctx.drawImage(img, 0, 0);
});
};
// good idea to set src attribute AFTER the onload handler is attached
img.src = 'http://l.yimg.com/dh/ap/default/121214/babydeer340.jpg';
关于css - IE9 Canvas 缩放问题。不会保持宽高比以适合容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13905183/