简体   繁体   English

HTML5画布drawImage图像大小不正确

[英]HTML5 canvas drawImage incorrect image size

Hello i have problem i try to drawing image on the canvas with drawImage function 50px x 50px on the 50px x 50px canvas, but i get smaller than i need. 您好我有问题我尝试在画布上使用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> 

Don't set a canvas's width and height through CSS. 不要通过CSS设置画布的宽度和高度。 This will stretch / compress the actual canvas, scaling the contents. 这将拉伸/压缩实际画布,缩放内容。

Use those old HTML width and height attributes instead: 请改用旧的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> 

These attributes actually change the canvas's context's width and height, resulting in a image that's exactly the size you expect it to be. 这些属性实际上会更改画布的上下文的宽度和高度,从而产生与您期望的大小完全相同的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM