2012-05-31 15 views
46

Estoy intentando escalar una imagen proporcionalmente al lienzo. Soy capaz de escalar con ancho fijo y altura como así:Lienzo drawImage scale

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

Pero sólo quiero cambiar el ancho y tienen la altura de cambiar el tamaño proporcionalmente. Algo como lo siguiente:

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

He buscado en todas partes en las que puedo pensar y no he visto si esto es posible.

Respuesta

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

Y si desea escalar adecuadamente la imagen de acuerdo con el tamaño de pantalla, aquí es la matemática que puede hacer: SI NO está usando jQuery, sustituya $ (ventana) .width con la opción equivalente apropiado.

   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

solución de @TechMaze es bastante bueno.

aquí está el código después de cierta corrección e introducción del evento image.onload. image.onload es demasiado esencial para abstenerse de cualquier tipo de distorsión.

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