Skip to content

Instantly share code, notes, and snippets.

Created August 14, 2012 13:30
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save anonymous/3349262 to your computer and use it in GitHub Desktop.
Save anonymous/3349262 to your computer and use it in GitHub Desktop.
$(document).ready(function() {
// create canvas
var canvas = document.createElement("canvas");
canvas.height = 300; // important! because default canvas size is 300x150
var ctx = canvas.getContext('2d');
// create img
var img = document.createElement("img");
// IMPORTANT adding shadow map - each area has different background color
// which is then used to identify the area (see the image to understand)
img.src = "/canvasmap/canvasmap_shadowmap.png";
// wait till it's loaded and redraw it into canvas (still neither canvas nor img are displayed)
img.onload = function(e) {
ctx.drawImage(img, 0, 0);
getMyImgData(ctx);
} // end img.onload
}); // end domready
function getMyImgData(ctx) {
// get pixel data from the canvas
var pix = ctx.getImageData(0, 0, 300, 300);
$("#map_wrapper").mousemove(function(e){
// each pixel is represented by 4 subsequent values in the data array, being red, green, blue, alpha
// datapos is the respective value for a pixel on [offsetX,offsetY] coordinates
var datapos = ((e.offsetY-2) * 300 * 4) + ((e.offsetX-1) * 4);
// will pick one of them, let's say the first one which is red channel, and read the color value there
var red = pix.data[datapos];
// others commented out. just for info purposes here
//var green = pix.data[datapos+1];
//var blue = pix.data[datapos+2];
//var alpha = pix.data[datapos+3];
// associative array of districts and e.g. their URLs
// IMPORTANT the 'key' in this array is actually the color value on the shadow map - this is the main idea of the example
var countries = {
// decimal color value: [sprite position, "country name"]
00: [5, "Poland"],
51: [6, "Germany"],
102: [1, "Czechia"],
153: [2, "Slovakia"],
187: [4, "Austria"],
221: [3, "Hungary"],
255: [0, "Nothing"]
}
// shift css background sprite
$("#map_wrapper").css("background-position", (countries[red][0])*(-300)+"px 0px").css("cursor","pointer");
// show me the country name
$("#url").text(countries[red][1]);
});
}
@GeekyTrash
Copy link

And how to import it in my html code?

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