2012-05-31 16 views
46

Sto provando a ridimensionare un'immagine in modo proporzionale alla tela. Sono in grado di scalare con larghezza fissa e altezza così:Disegno su telaImmagine ridimensionamento

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

Ma ho solo voglia di ridimensionare la larghezza e hanno l'altezza ridimensionare proporzionalmente. Qualcosa di simile a quanto segue:

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

ho cercato ovunque mi viene in mente e non ho visto se questo è possibile.

risposta

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

E se si vuole scalare correttamente l'immagine come per la dimensione dello schermo, qui è la matematica che si può fare: SE non si utilizza jQuery, sostituire $ (window) .width con opzione equivalente appropriata.

   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

soluzione di @TechMaze è abbastanza buono.

ecco il codice dopo una certa correttezza e introduzione dell'evento image.onload. image.onload è troppo essenziale per astenersi da qualsiasi tipo di distorsione.

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); 
} 
}