3

我似乎无法缩放由 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>

http://jsfiddle.net/VAXrL/535/

4

1 回答 1

0

我也希望这种行为在所有浏览器中都是一致的,但它看起来像 IE9 和其他几个将画布视为块级元素,因此您需要设置宽度和高度的样式。

画布元素将不得不依赖其大小的硬像素,因为它是光栅化的。一种方法是根据图像的原始大小和所需的比例来计算和设置这些像素。

我分叉了你的 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';
​
于 2012-12-17T16:42:46.393 回答