summaryrefslogtreecommitdiff
path: root/neighbor/neighbor.js
blob: 55176270a7354db4d527f400b19c8ca8b8b657dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
 * Neighbor.js by OKFocus - http://okfoc.us - @okfocus
 * Version 1.0
 * Licensed under MIT.
 *
 */

var neighbor = function(el){
  var base = this;
  base.el = document.querySelector(el);
  var img;

  var active = true, hovering = false;
  var canvas, imageData = null;

  base.init = function(){
    var url = base.el.src;

    img = base.el;
    img.onload = base.load;
    if (img.complete) {
      base.build( img );
    }
  };

  base.load = function(){
    base.build( img );
  }
  base.build = function( img ){
    if (canvas) return;
    canvas = document.createElement("canvas");
    var nw = canvas.width = img.naturalWidth;
    var nh = canvas.height = img.naturalHeight;

    var neighbor = document.createElement("canvas");
    var w, h, scaleW, scaleH;

    var bounds = img.getBoundingClientRect();
    w = neighbor.width = bounds.width;
    h = neighbor.height = bounds.height;

    scaleH = nh / h;
    scaleW = nw / w;

    var nctx = canvas.getContext( '2d' );
    nctx.drawImage( img, 0, 0 );
    nidd = nctx.getImageData( 0, 0, canvas.width, canvas.height )
    nid = nidd.data;

    var ctx = neighbor.getContext('2d');
    var idd = ctx.createImageData( w, h );
    var id = idd.data;

    for (var i = 0; i <= w; i++) {
      for (var j = 0; j <= h; j++) {
        var y = Math.floor( j * scaleH );
        var x = Math.floor( i * scaleW );
        var np = (y * nw + x ) * 4;
        var p = (j * w + i ) * 4;

        id[ p   ] = nid[ np   ]
        id[ p+1 ] = nid[ np+1 ]
        id[ p+2 ] = nid[ np+2 ]
        id[ p+3 ] = nid[ np+3 ]
      }
    }

    ctx.putImageData( idd, 0, 0 );

      base.el.parentNode.insertBefore( neighbor, base.el );
    neighbor.style.display = base.el.style.display;
    base.el.style.display = "none";
  }

  base.clamp = function (x, min, max) {
    return Math.max(min, Math.min(max, x));
  };

  base.init();
}