2012-05-31 8 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適切な同等のオプションとをREPLACE が。

   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); 
} 
} 
関連する問題