In the browser, can I get the color of the image that my mouse points to?

For me there is a web application for creating, not an image map, I would like to try something more elegant.

The story is that there will be a global map where different continents are indicated by different colors.

Say Australia is red and Asia is green.

Will there be a way, when my mouse vibrates in the shape of Australia, that my code will tell me that I am hanging over Australia, checking the color that my cursor points to?

I know that I can check the coordinates of the mouse on the image or something else, but I really want to get something that does not depend on predefined values ​​/ shapes / fields.

Any idea or suggestion would be highly appreciated. Thank you very much in advance.

+4
source share
2 answers

It depends on which element of your card. Certainly, some elements in browsers support canvas , but not for the entire page.

See the answers to my similar question: JavaScript eyedropper (specify the color of the pixel under the mouse cursor)

+7
source

Combining the various links found here on StackOverflow and other sites, I did this 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 used only canvas and one image, but if you need to use <map> for the image, this is also possible. I hope I helped!

+2
source

Source: https://habr.com/ru/post/1303800/


All Articles