Home > Articles

  • Print
  • + Share This
From the author of Loading the Images

Loading the Images

After creating the canvas, we need to populate it with an image. The following code uses an image element to texture the canvas:

var image = document.getElementById("textureImage");
var texture = canvas.texture(image);
canvas.draw(texture).update()         

In the snippet above, we used an image element that already existed on the web page. In our application, we need a slightly more complex means to load the image. Instead of dropping a large block of code here, let's go over it bit by bit.

We begin with the JavaScript code to create a file selector and assign a function named handleFile to it:

$('#richUI').append("<input id='openFile' type='file' />"); 
$('#openFile').get(0).addEventListener('change', self.handleFile, false); 

Our handleFile function responds to the change event (ProgressEvent) by constructing a FileReader object and trying to process the file. If the file has finished loading, the function proceeds to load the file and place it in a texture.

var files = evt.target.files;
if (files.length > 0) {
  var dataURL;
  var fr = new FileReader()
  fr.onload = (function(file) {
    return function(e) {
      if (e.target.readyState == 2) {
        var dataURL = e.target.result;
        var image = new Image();
        image.onload = function() {
            // Load image into texture
                    };
        image.src = dataURL;
      }
    }
  })(files[0]);
  fr.readAsDataURL(files[0]);
}

The FileReader API has several built-in functions that allow you to read a file as a data URL, text, binary String or an ArrayBuffer. In this case, we used readAsDataURL.

Now that we have the code for loading an image into a texture, let's start applying filters to it. When the user selects an effect from the drop-down menu, the left panel populates with controls corresponding to that effect. Figure 2 shows the user interface for applying a sepia effect.

Figure 2 Slider control for Sepia effect.

Following is the code for applying a sepia tone to an image. We use jQuery to create a slider dynamically and execute a function every time the value is changed.

self.sepia = function () {
        $('#richUI').empty();
        $('#richUI').append('<h3>Sepia</h3>');

        // Function to be executed on every change
        var func = function() {
            // Scale change to range 0 - 1.0
            var value = self.sepiaSlider.val()/100;
            self.canvas.draw(self.tex).sepia(value).update();
        };

        self.sepiaSlider = self.createSlider(0,100, func);
        // set value to 0 for no effect
        self.sepiaSlider.attr('value',0);

        $('#richUI').append(self.sepiaSlider);
}

Figure 3 shows the running application.

Figure 3 Image with increased sepia tone.

  • + Share This
  • 🔖 Save To Your Account