将图像作为页面背景从数组列表javascript中修复

时间:2016-07-13 11:03:28

标签: javascript

如果用户想要更改,我尝试添加图像作为html页面的背景。所以我做的是,我使用输入文件类型来访问本地文件夹,我也可以将它们设置为选择他们想要的图像。但现在我想如何制作用户选择的图像,使其固定为页面backgroundImage。这是我的代码。这主要是像桌面背景或智能手机壁纸

的index.html

<!DOCTYPE html>
<html>
<head>
    <title>Understanding File upload and File access Javascript</title>
</head>
<body>
    <input type = "file" id = "files" name = "files[]" multiple></input>
    <output id = "list"></output>
</body>
<script src = "fileaccess.js" type = "text/javascript"></script>
</html>

fileaccess.js

if(window.File && window.FileReader && window.FileList && window.Blob){
     alert("Yes, its supported in this browser");
}else{
     alert('The File APIs are not fully supported in this browser.');
}

function handleFileSelect(evt){
    var files = evt.target.files;
    var output = [];
    for(var i = 0, f; f = files[i]; i++){
        output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a',') - ',
                    f.size, 'bytes, last modified: ',
                    f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                     '</li>');
    }
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';

}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

请提供帮助!

1 个答案:

答案 0 :(得分:2)

您需要实例化FileReader,通过readAsDataURL()读取所选图片,并将结果数据网址分配给body.style.backgroundImage

如果您希望用户选择图像,您需要将文件加载到图像或画布元素,然后允许用户选择显示图像的一部分,最后将图像选择复制到关闭 - 画布。然后,您可以将画布的数据URL分配给body.style.backgroundImage

function imageToBackground(image, x, y, width, height) {
  var canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  var context = canvas.getContext("2d");
  context.drawImage(image, x, y, width, height, 0, 0, width, height);
  document.body.style.backgroundImage = "url(" + canvas.toDataURL() + ")";
}

function readImage(file, image) {
  var reader = new FileReader();
  reader.addEventListener("load", function() {
    image.src = reader.result;
  });
  reader.readAsDataURL(file);
}

var file = document.getElementById("file");
var image = document.getElementById("image");
var button = document.getElementById("button");

file.addEventListener("change", function(event) {
  var file = event.target.files[0];
  if (file) readImage(file, image);
});

button.addEventListener("click", function(event) {
  // Todo: let the user chose the region
  imageToBackground(image, 0, 0, 100, 100);
});
<input type="file" id="file">
<image id="image">
<input type="button" id="button" value="Set as background">

您现在需要为用户提供一种选择加载图像区域的方法。要么选择网上可用的许多图像裁剪插件中的一个,要么提出自己的实现。