2013-10-19 90 views
0

我有這樣的代碼(從網上被盜):在畫布上繪製圖像拉伸圖像?

function readIt() { 
    var reader = new FileReader(); 
    reader.onload = (function(e) { 
     var img = new Image(); 
     img.src = e.target.result; 
     var c = document.getElementById("canvas"); 
     var ctx = c.getContext("2d"); 
     ctx.drawImage(img, 0, 0); 
    } 
); 
    reader.readAsDataURL(document.getElementById('userImage').files[0]); 
} 

其中最多工作到一個點。畫布的寬度和高度設置爲圖像的大小,但僅顯示圖像的左上角 - 它看起來被拉伸,因此它適合分配給畫布的所有空間(足以顯示整個圖像 - 615px x 615px )。

如果我添加一個尺寸與畫布大小相同的元素,並將src指向文件系統中的圖像,它看起來很完美。

我使用的是Chrome瀏覽器,但它在Firefox中顯示的相同。

在此先感謝。

+0

的問題是使用CSS來指定高度和帆布的寬度。你知道爲什麼嗎? –

回答

1

的幾點思考:

  • 使用圖像的onload方法來給圖像足夠的時間在使用它之前加載。
  • 如果您使用css調整畫布 - 不要。而是調整畫布元素本身的大小。

下面是一些示例代碼:

var img=new Image(); 
img.onload=function(){ 

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

    // resize the canvas element to the same size as the image 
    // DON'T RESIZE WITH CSS -- your results will appear stretched 
    c.width=img.width; 
    c.height=img.height; 

    // draw the image onto the canvas 
    ctx.drawImage(img,0,0); 

} 
img.src=e.target.result;