summaryrefslogtreecommitdiff
path: root/neighbor.js
diff options
context:
space:
mode:
Diffstat (limited to 'neighbor.js')
-rw-r--r--neighbor.js80
1 files changed, 80 insertions, 0 deletions
diff --git a/neighbor.js b/neighbor.js
new file mode 100644
index 0000000..5517627
--- /dev/null
+++ b/neighbor.js
@@ -0,0 +1,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();
+}