2016-02-24 203 views
2

我試圖調整圖像尺寸的大小,同時保留其縱橫比。這似乎是一個非常簡單的任務,但我無法在任何地方找到答案。(關於JavaScript的Image()對象)。我可能錯過了一些非常明顯的東西。下面是我想實現:更改圖像()對象尺寸(寬度和高度)

var img = new window.Image(); 
img.src = imageDataUrl; 
img.onload = function(){ 
    if (img.width > 200){ 
     img.width = 200; 
     img.height = (img.height*img.width)/img.width; 
    } 
    if (img.height > 200){ 
     img.height = 200; 
     img.width = (img.width*img.height)/img.height; 
    } 
}; 

這是被拉伸到畫布上,像這樣前按比例調整圖像大小:context.drawImage(img,0,0,canvas.width,canvas.height);。但是它會出現,我不能直接改變Image()尺寸,所以它是怎麼做的?謝謝。

編輯:我還沒有正確解決圖像proportions使用交叉倍增。 @markE提供了一種獲得正確比例的簡潔方法。下面是我新的(工作)執行:

var scale = Math.min((200/img.width),(200/img.height)); 
img.width = img.width*scale; 
img.height = img.height*scale; 
clearCanvas(); //clear canvas 
context.drawImage(img,0,0,img.width,img.height); 
+0

,則應該設置個大小e圖像傳遞給['drawImage'](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage)。另外,一般來說,首先爲圖像設置一個裝載處理程序,然後再設置src。 – Teemu

+0

你能提供更好的測試細節嗎? - 像圖片參考和HTML。 – Sarhanis

+0

這是真的,謝謝你@Teemu但是,如果我設置像這樣的變量'context.drawImage(img,0,0,img.width,img.height);'或'context.drawImage(img,0,0 ,null,null);',它仍然伸展或不改變圖像尺寸。它會出現'Image()'沒有'.width'和'.height'變量? – TheMintyMate

回答

7

以下是如何比例縮放圖像:

function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){ 
    return(Math.min((maxW/imgW),(maxH/imgH))); 
} 

用法:

var canvas=document.getElementById("canvas"); 
 
var ctx=canvas.getContext("2d"); 
 

 
var img=new Image(); 
 
img.onload=start; 
 
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/balloon.png"; 
 
function start(){ 
 

 
    canvas.width=100; 
 
    canvas.height=100; 
 

 
    var w=img.width; 
 
    var h=img.height; 
 

 
    // resize img to fit in the canvas 
 
    // You can alternately request img to fit into any specified width/height 
 
    var sizer=scalePreserveAspectRatio(w,h,canvas.width,canvas.height); 
 

 
    ctx.drawImage(img,0,0,w,h,0,0,w*sizer,h*sizer); 
 

 
} 
 

 
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){ 
 
    return(Math.min((maxW/imgW),(maxH/imgH))); 
 
}
body{ background-color: ivory; } 
 
canvas{border:1px solid red;}
<h4>Original Balloon image resized to fit in 100x100 canvas</h4> 
 
<canvas id="canvas" width=100 height=100></canvas>

+1

不錯的使用'Math.min()'。 – TheMintyMate

+0

base64圖像也適用於它 - > https://jsfiddle.net/ej2rkarx/ – fearis

2

的圖像尺寸在構造函數中設置

new Image(width, height) 
// for proportionally consistent resizing use new Image(width, "auto") 

the context.drawImage() 

參數如下:

context.drawImage(image source, x-coordinate of upper left portion of image, 
y-coordinate of upper left portion of image,image width,image height); 

簡單positio n個與前兩個數字座標,然後將圖像手動與最後兩個(寬,高)調整大小

//ex. 
var x = 0; 
var y = 0; 
var img = new Image (200, "auto"); 
    img.src = "xxx.png"; 
context.drawImage(img,x,y,img.width,img.height); 
相關問題