2012-05-31 292 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); 
} 
}