图像大小与画布大小不匹配 [英] Image size doesn't match the canvas size

查看:236
本文介绍了图像大小与画布大小不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样做了画布,

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

然后尝试在我的脚本中将png放在画布上

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尺寸为312 * 212,尺寸与帆布尺寸相同。

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

但是,我的png文件在画布上展开了。因此,右边缘和底边缘从画布突出。

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

为什么我的png不适合?

Why my png doesn't fit in ??

推荐答案

所有画布都应指定宽度和高度属性

All canvas should have width and height attributes specified

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

宽度和高度不应使用'px'。
使用javascript:

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
});

这篇关于图像大小与画布大小不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆