首先,您需要找到图像和画布的纵横比。这是由以下人员完成的:
var canvasRatio = canvas.width / canvas.height,
imgRatio = img.width / img.height,
s = 1;
然后你需要像这样比较这些比率:
//the image is »more portrait«
//to fully cover the canvas
//scale by width
if (imgRatio < canvasRatio) {
s = canvas.width / img.width;
//image has the same, or a »more landscape«
//ratio than the canvas
//to cover scale by height
} else {
s = canvas.height / img.height;
}
//scale the context
ctx.scale(s, s);
cts.drawImage(â¦);
更新
if
):
var s = Math.max(canvas.width/img.width, canvas.height/img.height);
Math.min