2011-06-17 79 views
3

我想創建網頁,允許用戶將圖像拖放到頁面各個部分的框中,以便他們可以打印頁面與他們的圖像。將圖像拖放到網頁中並使用HTML File API自動調整它們的大小

我希望圖像在框中放置時自動調整大小。我將http://html5demos.com/file-api中的部分代碼與http://html5demos.com/file-api-simple的部分代碼組合在一起,以獲得我想要的內容。

在當前版本的代碼中(下圖),圖像寬度在您第一次將圖像放入方框但不是第二次調整圖像大小時調整大小。

任何建議如何讓圖像寬度自動調整大小,第一次將圖像放入盒子?

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset=utf-8 /> 
<meta name="viewport" content="width=620" /> 
<title>HTML5 Test</title> 
</head> 
<body> 
<header> 
     <h1>HTML5 Test 1</h1> 
</header> 
<style> 
    #holder { border: 10px dashed #ccc; width: 300px; height: 300px; margin: 20px auto;} 
    #holder.hover { border: 10px dashed #333; } 
</style> 
<article> 
    <div id="holder"></div> 
    <p id="status">File API & FileReader API not supported</p> 
    <p>Drag an image from your desktop on to the drop zone above to see the browser read the contents of the file - without uploading the file to any servers.</p> 
</article> 
<script> 
var holder = document.getElementById('holder'), 
    state = document.getElementById('status'); 

if (typeof window.FileReader === 'undefined') { 
    state.className = 'fail'; 
} else { 
    state.className = 'success'; 
    state.innerHTML = 'File API & FileReader available'; 
} 

holder.ondragover = function() { this.className = 'hover'; return false; }; 
holder.ondragend = function() { this.className = ''; return false; }; 
holder.ondrop = function (e) { 
    this.className = ''; 
    e.stopPropagation(); 
    e.preventDefault(); 

    var file = e.dataTransfer.files[0], 
     reader = new FileReader(); 
    reader.onload = function (event) { 
    var img = new Image(); 
    img.src = event.target.result; 
    // note: no onload required since we've got the dataurl...I think! :) 
    if (img.width > 300) { // holder width 
     img.width = 300; 
    } 
    holder.innerHTML = ''; 
    holder.appendChild(img); 
    }; 
    reader.readAsDataURL(file); 

    return false; 
}; 
</script> 

</body> 
</html> 

回答

0

是的。使用這個傢伙的來源:

http://imgscalr.com/

+0

感謝您的建議。不幸的是,這種方法是行不通的,因爲我的目標是讓孩子們使用這張照片和自己的照片,出於安全原因,我不想將照片上傳到服務器。我希望孩子們能夠將照片拖放到網頁上並進行打印,而無需將文件上傳到任何服務器。 – gurdy 2011-07-02 23:01:28

+0

再看一遍。這傢伙已經提供了他的消息來源。假設他的許可證允許,分叉代碼並進行所需的更改。 – 2011-07-04 12:12:31

相關問題