开发者

dragging and dropping images into a Web page and automatically resizing them with HTML File API

I want to create Web pages that allow users to drag and drop images into boxes in various parts of the page, so that they can then print the pages with their images.

I want the image to automatically resize when it's dropped in the box. I combined some of the code at http://html5demos.com/file-api with some of the code at http://html5demos.com/file-api-simple to get something like I want.

In the current version of the code (below), the image width does not resize the first time you drop the image into the box, but it does the second time.

Any suggestions how I can get the image width to resize automatically the first time you drop the image into the box?

<!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>


I found a simple answer that I think works really well for my needs, based on a bit of CSS in http://demos.hacks.mozilla.org/openweb/DnD/dropbox.css used for http://demos.hacks.mozilla.org/openweb/DnD/.

In the code I included in my question above, I added this to the CSS code:

   #holder > * {
    display: block;
    margin: auto;
    max-width: 300px;
    max-height: 300px;
}

and I deleted this:

    if (img.width > 300) { // holder width
      img.width = 300;
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜