你好我有问题我尝试在50px x 50px画布上使用drawImage
函数50px x 50px在画布上绘制图像,但是我比我需要的要小。
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>
答案 0 :(得分:15)
不要通过CSS设置画布的宽度和高度。这将拉伸/压缩实际画布,缩放内容。
请改用旧的HTML width
和height
属性:
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';
&#13;
<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>
&#13;
这些属性实际上会改变画布的上下文宽度和高度,从而使图像的大小与您期望的大小完全相同。