2017-09-20 3 views
0

drawImage를 사용하여 이미지의 크기를 조정하려고하지만 크기를 유지하려고합니다. 나는 ... 지금까지이drawImage - 크기 조절 및 크기 조절

window.onload = function() { 
 
    var c = document.getElementById("myCanvas"); 
 
    var ctx = c.getContext("2d"); 
 
    var img = document.getElementById("scream"); 
 
    ctx.drawImage(img, 0, 0, 600, 428); 
 
}
<p>Image to use:</p> 
 
<img id="scream" width="400" height="300" src="http://lorempixel.com/1280/960/sports/" alt="The Scream"> 
 

 
<p>Canvas:</p> 
 
<canvas id="myCanvas" width="428" height="600" style="border:2px solid black;"> 
 
Your browser does not support the HTML5 canvas tag. 
 
</canvas>
그때가되고있는 정확한 치수를 넣으면 내가, 이미지 하단의 공백을 잃고 컨테이너를 채울 수 있도록 노력하고

뻗어있다.

누구나 방향을 가르쳐 줄 수있는 예가 있습니까?

+1

비율을 유지한다는 의미입니까? https://stackoverflow.com/questions/21961839/simulation-background-size-cover-in-canvas 또는 https://stackoverflow.com/questions/34428723/ 옵션 중 하나와 같습니다. – Kaiido

답변

1

먼저 이미지와 캔버스의 종횡비를 찾아야합니다. 비율이 1보다 작은 경우는, 풍경 (간주)되어 같거나 1보다 높으면 다음은, 다른 초상화,

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(…); 

UPDATE

그것은이 방법으로도 짧은 (NO 비율, 더 if) :

var s = Math.max(canvas.width/img.width, canvas.height/img.height); 

에 이미지를 맞추려면 Math.min을 사용하십시오.

+0

지금 읽어 주셔서 감사합니다. – fightstarr20