问题
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