Image size doesn't match the canvas size

好久不见. 提交于 2020-02-05 04:12:13

问题


I made canvas like this ,

<canvas id="mainCanvas" style="width:310px;height:212px;">
</canvas>

then try to put png on the canvas in my script

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

var img= new Image();
img.src = "img/player.png";

context.drawImage(img,0,0,310,212);

my plyer.png size is 312 *212 , the same size as canvas size.

However,my png file is expansioned on the canvas. Consequently, right edge and bottom edge protrude from the canvas.

Why my png doesn't fit in ??


回答1:


All canvas should have width and height attributes specified

<canvas width="310" height="212"></canvas>

Width and height shouldn't use 'px'. With javascript use:

var c = document.querySelector('canvas');
c.width=310;
c.height=212;// as  Ken Fyrstenberg mentioned

Also be sure to wait till image will load.

img.onload(function(){
   //drawimage
});



回答2:


You need to apply the size as an attribute not styles. Try this:

 <canvas id="mainCanvas" width="310" height="212">
 </canvas>


来源:https://stackoverflow.com/questions/28611849/image-size-doesnt-match-the-canvas-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!