There is a web application for me to build, and rather than image map, I would like to try something more elegant.
The story is, there gonna be a global map where different continents are denoted by different colors.
Say Australia is red and Asia is green.
Will there be a way that when my mouse is hovering on the shape of Australia that my code will tell me that I am hovering on Australia by checking for the color where my cursor is currently pointing at?
I know I can check for mouse coordinates on image or something else, but I really want to get something that is not depending on pre-defined values/sh开发者_JS百科apes/margins.
Any idea and suggestion would be much appreciated. Thanks a lot in advance.
It depends on what kind of element your map is. It is definitely possible for certain elements in browsers that support canvas
, but not for the whole page.
See the answers to my similar question: JavaScript eyedropper (tell colour of Pixel under mouse cursor)
Merging various references found here in StackOverflow and in other sites, I did so using javascript and JQuery:
<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script src="jquery.js"></script>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = 'photo_apple.jpg';
context.drawImage(img, 0, 0);
};
function findPos(obj){
var current_left = 0, current_top = 0;
if (obj.offsetParent){
do{
current_left += obj.offsetLeft;
current_top += obj.offsetTop;
}while(obj = obj.offsetParent);
return {x: current_left, y: current_top};
}
return undefined;
}
function rgbToHex(r, g, b){
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
$('#myCanvas').click(function(e){
var position = findPos(this);
var x = e.pageX - position.x;
var y = e.pageY - position.y;
var coordinate = "x=" + x + ", y=" + y;
var canvas = this.getContext('2d');
var p = canvas.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
alert("HEX: " + hex);
});
</script>
<img src="photo_apple.jpg"/>
</body>
</html>
Here I only used canvas and one image, but if you need to use <map>
over the image, it's possible too.
I hope I have helped!
精彩评论