HTML5 canvas drawImage 图像大小不正确

HTML5 canvas drawImage incorrect image size

你好,我有问题我尝试在 canvas 上使用 drawImage 函数 50px x 50px 在 50px x 50px canvas 上绘制图像,但我变得比我需要的要小。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.onload = function() {
    $("canvas").css("width", 50);
    $("canvas").css("height", 50);
    ctx.drawImage(img, 0, 0, 50, 50); //bad here why not drawing 50x50px image on the canvas?           
}
img.src = 'http://www.w3schools.com/tags/planets.gif';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="http://www.w3schools.com/tags/planets.gif" width="100" height="100" style="position: absolute; top: 0px; left: 0px">
<canvas id="canvas" style="position: absolute; top: 0px; left: 120px; border: 1px solid #000"></canvas>

不要通过CSS设置canvas的宽度和高度。这将拉伸/压缩实际 canvas,缩放内容。

改用那些旧的 HTML widthheight 属性:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0, 50, 50);
}
img.src = 'http://www.w3schools.com/tags/planets.gif';
<img src="http://www.w3schools.com/tags/planets.gif" width="100" height="100" style="position: absolute; top: 0px; left: 0px">
<canvas
    id="canvas"
    style="position: absolute; top: 0px; left: 120px; border: 1px solid #000"
    width="50"
    height="50">
</canvas>

这些属性实际上会更改 canvas 上下文的宽度和高度,从而使图像的大小完全符合您的预期。