RSN RSN - 3 months ago 11
Javascript Question

fix image as page background from the array list javascript

I'm trying to add an image as a background for the html page if the user wants to change.So what I did is, I used input file type to access the local folder and I can also make them to select the image whatever they want. But now I want to how can I make the image which was selected by the user to make it fixed as the page backgroundImage. Here is my code.This is mostly like a desktop background or smartphone wallpaper.


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


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

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

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

Please give some help!


You need to instantiate a FileReader, read the chosen image via readAsDataURL() and assign the resulting data url to

If you want the user to chose a selection of the image, you need to load the file to an image or canvas element, then allow the user to select a part of the displayed image and finally copy the image selection to an off-screen canvas. You can then assign the canvas's data url to

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); = "url(" + canvas.toDataURL() + ")";

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

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

file.addEventListener("change", function(event) {
  var file =[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">

You would now need to provide the user with a way to select a region of the loaded image. Either chose one of the many image cropping plugins available on the net or come up with your own implementation.