Skip to content

Instantly share code, notes, and snippets.

@thirdknife
Created May 4, 2015 13:33
Show Gist options
  • Select an option

  • Save thirdknife/0b9208f8a0e0732eb791 to your computer and use it in GitHub Desktop.

Select an option

Save thirdknife/0b9208f8a0e0732eb791 to your computer and use it in GitHub Desktop.
$(document).ready(function() {
var canvas = $('canvas');
var ctx = canvas[0].getContext( '2d' );
var img = new Image;
img.crossOrigin = '';
img.src = 'http://i.imgur.com/xG8sIPp.jpg';
img.onload = function() {
var width = img.width;
var height = img.height;
canvas.attr( 'width', width );
canvas.attr( 'height', height );
setTimeout( function() {
ctx.clearRect( 0, 0, width, height );
ctx.drawImage( img, 0, 0, width, height );
img.remove();
canvas.setHover([
{
color: [ 121, 145, 71, 255 ],
newColor: [ 255, 0, 0, 255 ], // you can set this to show the detected area
difference: 36, // the color/alpha values can have a difference of 36
func: function() { // this is called on hover of the detected points
canvas.css( 'cursor', 'pointer' );
console.log( this );
}
},
{
difference: 10,
color: [ 0, 0, 0, 255 ],
func: function() {
console.log( this );
}
}
]);
});
};
});
$.fn.setHover = function( options ) {
var canvas = this;
var ctx = this[0].getContext( '2d' );
var imgData = ctx.getImageData( 0, 0, this.width(), this.height() );
var rgbaData = imgData.data;
var hover = [];
for( var i = 0; i < rgbaData.length; i += 4 ) {
$.each( options, function() {
if( rgbaData[i + 0] - this.difference < this.color[0] && rgbaData[i + 0] + this.difference > this.color[0] &&
rgbaData[i + 1] - this.difference < this.color[1] && rgbaData[i + 1] + this.difference > this.color[1] &&
rgbaData[i + 2] - this.difference < this.color[2] && rgbaData[i + 2] + this.difference > this.color[2] &&
rgbaData[i + 3] - this.difference < this.color[3] && rgbaData[i + 3] + this.difference > this.color[3]
) {
// x-Coord: (i / 4) % canvas.width()
// y-Coord: Math.floor((i / 4) / canvas.width())
if( !hover[(i / 4) % canvas.width()] ) hover[(i / 4) % canvas.width()] = [];
hover[(i / 4) % canvas.width()].push({
y: Math.floor((i / 4) / canvas.width()),
props: this
});
if( this.newColor ) {
rgbaData[i] = this.newColor[0];
rgbaData[i + 1] = this.newColor[1];
rgbaData[i + 2] = this.newColor[2];
rgbaData[i + 3] = this.newColor[3];
}
}
});
}
imgData.data = rgbaData;
ctx.putImageData( imgData, 0, 0 );
canvas.on( 'mousemove', function( event ) {
if( hover[event.offsetX || event.originalEvent.layerX] ) {
$.each( hover[event.offsetX || event.originalEvent.layerX], function( i, data ) {
if( data.y === (event.offsetY || event.originalEvent.layerY) ) {
data.props.func();
return false;
} else {
noHover();
}
});
} else {
noHover();
}
});
function noHover() {
// close Tooltip, or do something else
canvas.css( 'cursor', '' );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment