Skip to content

Instantly share code, notes, and snippets.

@xiaojue
Created September 5, 2012 04:12
Show Gist options
  • Select an option

  • Save xiaojue/3630265 to your computer and use it in GitHub Desktop.

Select an option

Save xiaojue/3630265 to your computer and use it in GitHub Desktop.
(function() {
$.fn.grayScan = function(options) {
var _config = {
direction: 'top',
timer: 10
},
T = null;
$.extend(_config, options);
function grayscale(src) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = src;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (var y = 0; y < imgPixels.height; y++) {
for (var x = 0; x < imgPixels.width; x++) {
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
function movehandle(e) {
var self = this;
if (T) clearTimeout(T);
T = setTimeout(function() {
var x = e.clientX - $(self).offset().left,
y = e.clientY - $(self).offset().top;
var mask = $(self).closest('.wrap').find('.J_mask');
if (_config.direction == 'left') mask.width(x);
else if (_config.direction == 'top') mask.height(y);
},
_config.timer);
}
$(this).each(function() {
var src = $(this).attr('src'),
height = $(this).height(),
width = $(this).width();
if (_config.direction == 'left') width = 0;
else if (_config.direction == 'top') height = 0;
$(this).wrap("<div class='wrap' style='display:inline-block'>").clone().attr('class', 'J_Clone').insertBefore(
$(this).closest('.wrap').find('.J_Clone').wrap('<div class="J_mask" style="overflow:hidden;height:' + height +
$(this).attr('src', grayscale(src));
$(this).bind('mousemove', movehandle);
$(this).closest('.wrap').find('.J_mask').bind('mousemove', movehandle);
});
return this;
};
})();
@xiaojue
Copy link
Copy Markdown
Author

xiaojue commented Sep 5, 2012

啊,给朋友写的插件。你的意思是movehandle和grayscale挂到$.fn.prototype上吗?没必要。。就2函数,这么放着就行。似有的函数不对外公开,扔到这里就成了。

@xiaojue
Copy link
Copy Markdown
Author

xiaojue commented Sep 5, 2012

似有=>私有。

这代码实现的是一个图片变灰色外加扫描图的特效。

@xiaojue
Copy link
Copy Markdown
Author

xiaojue commented Sep 5, 2012

$.fn 其实就是$的prototype。。

@myjack
Copy link
Copy Markdown

myjack commented Mar 26, 2013

unexpected token this

@myjack
Copy link
Copy Markdown

myjack commented Mar 26, 2013

unexpected token this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment