gqlbuw
Last Updated: March 02, 2016
·
2.269K
· kenju

Introduction ~ Created Instagram Filter with JavaScript

Introduction ~ Created Instagram Filter with JavaScript

One day, I was learning canvas of HTML5 protocol just for fun. Suddenly, an interesting idea came upon to me. "How about creating instagram or twitte's image-enhancing filters with canvas and js?". Soon after that I began creating such filters with HTML5/CSS3/JS, with a bunch of swings and roundabouts. This post is to introduce how I created the filter and whay I have learnt through the fun work on the weekend.

Personally, the filter is not perfectly imitated yet, so I am welcoming your advice or comments.

Github

<a href="https://github.com/KENJU/instagram_js_filter">![screenshot.png](https://qiita-image-store.s3.amazonaws.com/0/48264/bf9dc83e-5ede-07a3-964a-272882ee0e66.png "Screenshot")</a>

Extract pixels from images with canvas

kobito.1436582869.937282.png

With getContext('2d') and getImageDate(), you can extranc image pixels like below codes. This is the first step for creating filters.


Filter.canvas.getPixels = function(img) {
  var canvas,
      context
  ;
  canvas = Filter.canvas.getCanvas(img.width, img.height);
  context = canvas.getContext('2d');
  context.drawImage(img, 0, 0);
  return context.getImageData(0, 0, canvas.width, canvas.height);
};

Grayscale, Sepia, and Mirroring Effects were Easy

As a return of context.getImageData(), you can get an array that is composed of RGB + Alpha data of each pixels.


var pixels = 
  [ 15, 16, 28, 255, // Red, Green, Blue, Alpha of 1st pixel
    22, 51, 59, 255, // Red, Green, Blue, Alpha of 2nd pixel
    33, 55, 59, 255, // Red, Green, Blue, Alpha of 3rd pixel
    ...
  ];

Therefore, if you convert those RGB + Alpha data, you can create a new image with interesting effects as follows.

Example 1: Grayscale

grayscale


// grayscale
Filter.grayscale = function(pix){
  for (var i = 0, n = pix.length; i < n; i += 4){
    // calculated from NTSC
    var grayscale = pix[i] * .29 + pix[i+1] * .58 + pix[i+2] * .11;
    pix[i]    = grayscale;
    pix[i+1]  = grayscale;
    pix[i+2]  = grayscale;
  };
};

Example 2: Sepia

sepia


Filter.sepia = function(pix){
  for (var i = 0, n = pix.length; i < n; i += 4){
    pix[i]    = pix[i]    * 1.07;
    pix[i+1]  = pix[i+1]  * .74;
    pix[i+2]  = pix[i+2]  * .43;
  }
};

Example 3: Horizontal Mirroring