Dynamic Image Map Based on Pixel Colour

Share this article

So today I created a html image map which creates dynamic links based on the color of the pixel that the user clicked. The reason for creating this was because the map was a vector map of the world and as you know all countries have varying sizes and it would be impossible to create a normal point/array based image map… it would simple be too huge to store and would take too long to load.

Pro’s of this method

  • It loads really fast
  • No need to know what areas of the image are covered by what for links
  • Image areas can be any shape or size

How it works

dynamic-image-map-process
  1. User clicks anywhere on the image
  2. jQuery captures the x and y coordinates of where the user clicked
  3. x and y coordinates sent to PHP control script via Ajax
  4. PHP script gets the image locally and picks the pixel colour at the x and y coordinates
  5. PHP script gets the country that matches the hex colour value
  6. PHP script sends back the url of the page for that country
  7. jQuery redirects to the page returned via Ajax call

Instructions on how to setup:

Create the image with unique hex values (I used adobe illustrator with a free vector based image). vector-map-illustrator Store the hex colour values of the pixels contained within the boundaries of the each country in your database. database-hex-codes jQuery Code:
jQuery(document).ready(function($) {
	$('#theworldmapimage').live('click', function(ev) {
	   var X = $(this).offset().left;
	   var Y = $(this).offset().top;
	   mouseX = ev.pageX - X;
	   mouseY = ev.pageY - Y;
	   //FIX X AXIS ERORR MARGIN
	   //	mouseY -= 5;
	   if (mouseX > 500) { mouseX -= 13; }
	   //alert("x="+mouseX+" y="+mouseY);
		$.get("../php/php-functions/phpfunc-imagemap.php",{x: mouseX ,y: mouseY}, function(data){
			//alert(data);
			if (data != '') {
				//alert(data + " " +"x="+mouseX+" y="+mouseY);
				window.location.replace(data); //load the url of the clicked country
			}
			else {
				//alert("no data");
			}
		});
	});
});
PHP Code:
< ?php
if(isset($_REQUEST['x'])) {
    $x = $_REQUEST['x']; $y = $_REQUEST['y'];
    $im = imagecreatefrompng($domain."/images/worldmap-coloured.png");
    $rgb = imagecolorat($im, $x, $y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;

    function rgb2html($r, $g=-1, $b=-1)
    {
        if (is_array($r) && sizeof($r) == 3)
            list($r, $g, $b) = $r;
        $r = intval($r); $g = intval($g);
        $b = intval($b);
        $r = dechex($r<0?0:($r>255?255:$r));
        $g = dechex($g<0?0:($g>255?255:$g));
        $b = dechex($b<0?0:($b>255?255:$b));
        $color = (strlen($r) < 2?'0':'').$r;
        $color .= (strlen($g) < 2?'0':'').$g;
        $color .= (strlen($b) < 2?'0':'').$b;
        return $color;
    }

    $hex = rgb2html($r, $g, $b);
    //echo ("R".$r." G".$g." B".$b."  hex=#".$hex);
    $debug = ("R".$r." G".$g." B".$b."  hex=#".$hex);
    $html = "";

    $qry = "SELECT country FROM `countries` WHERE hex_colour= '".$hex."' LIMIT 1;";
    if (mysql_query($qry)) {
        $result = mysql_query($qry);
        while ($row = mysql_fetch_array($result,MYSQL_ASSOC)){
           $country_filename = convertToFileName($row{'country'});
            $html = $domain."/".$country_filename."/";
            $debug .= " " . $country_filename;
        }
    }
    mysql_close($dbh);
    echo $html;
}
?>
The final image looks like this: worldmap See Demo (Click on the “Show world map” to show the dynamic image map, then click on any country).

Frequently Asked Questions (FAQs) about Dynamic Image Map Based on Pixel Colour

How can I create a dynamic image map based on pixel color?

Creating a dynamic image map based on pixel color involves several steps. First, you need to have an image with different pixel colors. Then, you need to use a programming language like PHP to read the image and get the color of each pixel. You can use the imagecolorat() function in PHP to get the color of a pixel at a specific point. After getting the color, you can create an image map by assigning different areas of the image to different colors. This way, when a user clicks on a certain color, they will be directed to a specific area of the image map.

What is the use of imagecolorat() function in PHP?

The imagecolorat() function in PHP is used to get the color of a pixel at a specific point in an image. It returns the color of the pixel as an integer. This function is very useful when you want to create a dynamic image map based on pixel color. By using this function, you can get the color of each pixel in the image and assign different areas of the image map to different colors.

How can I assign different areas of the image map to different colors?

Assigning different areas of the image map to different colors involves using the imagecolorat() function in PHP to get the color of each pixel in the image. After getting the color, you can use the imagemap() function to assign different areas of the image map to different colors. This way, when a user clicks on a certain color, they will be directed to a specific area of the image map.

Can I use other programming languages to create a dynamic image map based on pixel color?

Yes, you can use other programming languages to create a dynamic image map based on pixel color. However, PHP is commonly used because it has built-in functions like imagecolorat() and imagemap() that make the process easier. Other languages like JavaScript and Python can also be used, but they may require additional libraries or modules to perform the same tasks.

What are the benefits of creating a dynamic image map based on pixel color?

Creating a dynamic image map based on pixel color has several benefits. First, it allows you to create interactive images where users can click on different colors to be directed to different areas of the image map. This can enhance the user experience and make your website more engaging. Second, it allows you to create complex image maps without having to manually define each area. This can save you a lot of time and effort.

How can I handle errors when creating a dynamic image map based on pixel color?

When creating a dynamic image map based on pixel color, you may encounter errors such as invalid image format or invalid pixel coordinates. To handle these errors, you can use error handling functions in PHP like set_error_handler() and trigger_error(). These functions allow you to define custom error messages and actions when an error occurs.

Can I use dynamic image maps based on pixel color for responsive design?

Yes, you can use dynamic image maps based on pixel color for responsive design. By using CSS and JavaScript, you can make the image map scale and resize according to the screen size. This way, the image map will look good on all devices, from desktops to mobile phones.

How can I optimize the performance of a dynamic image map based on pixel color?

To optimize the performance of a dynamic image map based on pixel color, you can use techniques like caching and image compression. Caching allows you to store the color data of the image so that you don’t have to read the image every time. Image compression reduces the size of the image without significantly affecting its quality, which can make the image load faster.

Can I use dynamic image maps based on pixel color for SEO?

Yes, you can use dynamic image maps based on pixel color for SEO. By adding alt text and title attributes to the areas of the image map, you can provide additional information to search engines about the content of the image. This can help improve the visibility of your website in search engine results.

How can I test a dynamic image map based on pixel color?

To test a dynamic image map based on pixel color, you can use tools like browser developer tools and online image map testers. These tools allow you to inspect the image map and see how it behaves when you click on different colors. You can also use automated testing tools to test the image map on different devices and screen sizes.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

ajax image mapDynamic Image Map linksjQuerypixel colour image mapworld vector map hex
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form