Development Tip

캔버스에 맞게 이미지 크기 조정

yourdevel 2020. 11. 12. 20:24
반응형

캔버스에 맞게 이미지 크기 조정


사용자가 이미지를 업로드 할 수있는 양식이 있습니다.

이미지가로드되면 서버로 다시 전달하기 전에 파일 크기를 줄이기 위해 이미지 크기를 조정합니다.

이를 위해 캔버스에 배치하고 거기에서 조작합니다.

이 코드는 320 x 240px 크기의 캔버스로 캔버스에 크기가 조정 된 이미지를 렌더링합니다.

ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

... 여기서 canvas.width 및 canvas.height는 원본 이미지의 크기를 기준으로 한 이미지 높이 및 너비 xa 배율입니다.

하지만 코드를 사용할 때 :

ctx.drawImage(img, 0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height

... 캔버스에서 이미지의 일부만 가져옵니다.이 경우 왼쪽 상단 모서리입니다. 실제 이미지 크기가 320x240 캔버스 크기보다 크더라도 캔버스에 맞게 전체 이미지를 '크기 조정'해야합니다.

따라서 위 코드의 경우 너비와 높이는 최종 이미지 크기 인 1142x856입니다. 양식이 제출 될 때 서버에 beck을 전달하기 위해 해당 크기를 유지해야하지만 사용자를 위해 캔버스에 더 작은보기 만 표시되기를 원합니다.

내가 여기서 무엇을 놓치고 있습니까? 누구든지 올바른 방향으로 나를 가리킬 수 있습니까?

미리 감사드립니다.


소스 이미지 (img) 크기를 첫 번째 직사각형으로 제공합니다.

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

두 번째 사각형은 대상 크기 (원본 사각형의 크기가 조정 됨)가됩니다.

2016/6 업데이트 : 종횡비 및 위치 지정 (CSS의 "표지"방법) 확인 :
시뮬레이션 배경 크기 : 캔버스의 표지


두 번째 호출에서 소스 크기를 대상 크기로 설정하는 데 오류가 발생했습니다.
어쨌든 크기가 조정 된 이미지에 대해 동일한 종횡비를 원하므로 계산해야합니다.

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

또한 이미지를 중앙에 배치하고 싶다고 가정하므로 코드는 다음과 같습니다.

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

여기 jsbin에서 볼 수 있습니다 : http://jsbin.com/funewofu/1/edit?js,output

참고 URL : https://stackoverflow.com/questions/23104582/scaling-an-image-to-fit-on-canvas

반응형