Image size doesn't match the canvas size

2019-08-10 19:24发布

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 ??

标签: html5 canvas png
2条回答
孤傲高冷的网名
2楼-- · 2019-08-10 19:29

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

 <canvas id="mainCanvas" width="310" height="212">
 </canvas>
查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-10 19:43

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
});
查看更多
登录 后发表回答