2014-04-18 33 views
0

我可以將圖像上傳到瀏覽器並將其轉換爲BLOB。之後,我嘗試將其繪製到畫布中,但未被識別。我有一種感覺,這是我想念的小事,但我看不到它。任何幫助都是極好的!Blob圖像不會進入使用javascript的畫布

var resize_img = 
function(){ 

    var file = document.getElementById("add_img").files; 

    // add in file type checker 

    // Create img element to PREVIEW 
    var img = document.createElement("img"); 
    img.src = window.URL.createObjectURL(file[0]); 


    // Draw image to CANVAS 
    var canvas_e = document.getElementById("canvas_img"); 
    var ctx = canvas_e.getContext("2d"); 
    ctx.drawImage(img, 0, 0); 

    //Resize Image 
    var MAX_WIDTH = 800; 
    var MAX_HEIGHT = 600; 
    var width = img.width; 
    var height = img.height; 

    if (width > height) { 
    if (width > MAX_WIDTH) { 
     height *= MAX_WIDTH/width; 
     width = MAX_WIDTH; 
    } 
    } else { 
    if (height > MAX_HEIGHT) { 
     width *= MAX_HEIGHT/height; 
     height = MAX_HEIGHT; 
    } 
    } 
    canvas_e.width = width; 
    canvas_e.height = height; 
    ctx.drawImage(img, 0, 0, width, height); 


    //Push Data 
    var dataurl = canvas_e.toDataURL("image/png"); 
    console.log(dataurl); 

} 

HTML

<!DOCTYPE html> 
<html> 
    <head> 
     <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
    <meta content="utf-8" http-equiv="encoding"> 
    <!-- CSS --> 
    <link href="css/main.css" rel="stylesheet" type="text/css" > 
    </head> 
    <body> 
     <input type="file" id="add_img" onchange="resize_img()"> 
     <canvas id="canvas_img"></canvas> 
     <!-- JS --> 
     <script src="js/main.js" type="text/javascript"></script> 
    </body> 
</html> 
+0

代碼將工作[0], img.src = window.URL.createObjectURL(blob) – sudhnk

回答

1

把帆布代碼img.onload =函數(){....}如果傳遞斑點替換文件

+0

工作就像一個魅力!謝謝! –