我似乎无法缩放由IE9中固定容器内的图像填充的画布。有谁知道一个工作?我记得读过一些关于IE如何将画布视为块元素的其他线程
<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>
答案 0 :(得分:0)
我也希望这种行为在所有浏览器中都是一致的,但它看起来像IE9和其他几个人将画布视为块级元素,所以你需要设置宽度和高度的样式。
canvas元素必须依赖于其大小的硬像素,因为它是光栅化的。一种方法是基于图像的原始尺寸和期望的比例来计算和设置这些像素。
我分叉你的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';