2012-05-31 4 views
46

캔버스에 비례하여 이미지의 크기를 조절하려고합니다.캔버스 drawImage 스케일링

context.drawImage(imageObj, 0, 0, 100, 100) 

하지만 난 단지 비례 적으로 크기를 조정 폭을 크기를 조정할와 높이를 가지고 : 난 너무로 고정 폭과 높이를 확장 할 수 있어요. 다음과 같은 것 :

context.drawImage(imageObj, 0, 0, 100, auto) 

내가 생각할 수있는 모든 곳을 보았습니다. 가능하다면 보지 못했습니다.

답변

69
context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height/imageObj.width) 
2

그리고 당신은 제대로 화면 크기에 따라 사진의 크기를 조절하려면, 여기 당신이 할 수있는 수학입니다 : 당신이 jQuery를 사용하지 않는 경우, $ (창) .width 적절한 해당하는 옵션으로 교체 은.

   var imgWidth = imageObj.naturalWidth; 
       var screenWidth = $(window).width() - 20; 
       var scaleX = 1; 
       if (imageWdith > screenWdith) 
        scaleX = screenWidth/imgWidth; 
       var imgHeight = imageObj.naturalHeight; 
       var screenHeight = $(window).height() - canvas.offsetTop-10; 
       var scaleY = 1; 
       if (imgHeight > screenHeight) 
        scaleY = screenHeight/imgHeight; 
       var scale = scaleY; 
       if(scaleX < scaleY) 
        scale = scaleX; 
       if(scale < 1){ 
        imgHeight = imgHeight*scale; 
        imgWidth = imgWidth*scale;   
       } 
       canvas.height = imgHeight; 
       canvas.width = imgWidth; 
       ctx.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight); 
3

@TechMaze의 용액이 아주 좋다.

여기에 image.onload 이벤트의 정확성과 도입 후의 코드가 있습니다. image.onload은 어떤 종류의 왜곡도 기피하기에는 너무 중요합니다.

function draw_canvas_image() { 

var canvas = document.getElementById("image-holder-canvas"); 
var context = canvas.getContext("2d"); 
var imageObj = document.getElementById("myImageToDisplayOnCanvas"); 

imageObj.onload = function() { 
    var imgWidth = imageObj.naturalWidth; 
    var screenWidth = canvas.width; 
    var scaleX = 1; 
    if (imgWidth > screenWidth) 
     scaleX = screenWidth/imgWidth; 
    var imgHeight = imageObj.naturalHeight; 
    var screenHeight = canvas.height; 
    var scaleY = 1; 
    if (imgHeight > screenHeight) 
     scaleY = screenHeight/imgHeight; 
    var scale = scaleY; 
    if(scaleX < scaleY) 
     scale = scaleX; 
    if(scale < 1){ 
     imgHeight = imgHeight*scale; 
     imgWidth = imgWidth*scale;   
    } 

    canvas.height = imgHeight; 
    canvas.width = imgWidth; 

    context.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight); 
} 
}