您好,我有问题我尝试drawImage
在50px x 50px的画布上以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>
不要通过CSS设置画布的宽度和高度。这将拉伸/压缩实际的画布,缩放内容。
改用那些旧的HTMLwidth
和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';
<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>
这些属性实际上会更改画布上下文的宽度和高度,从而生成的图像恰好是您期望的大小。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句