Navigate through PNG image - proceed only if the clicked area is transparent

Imagine having an image that looks like this:

https://i.sstatic.net/Ab6aW.jpg

I am looking to make it so that when I click on the transparent areas of the image, the click should pass through to the element below. However, if I click on a non-transparent area, the image itself should receive the click event.

Is it possible to achieve this effect?

Answer №1

  1. To begin, create a temporary canvas.
  2. Retrieve the click coordinates on the overlay image by clicking.
  3. Use the retrieved coordinates to fill your canvas with the corresponding image data.
  4. Check the Alpha channel data of the 1px image section from the canvas.
    If the Alpha channel data is 0, then it's considered as transparent.
  5. If the pixel is transparent, disable the pointerEvents and get the element underneath using Document.elementFromPoint
    Then trigger a "click" event on that element.
  6. Once done, revert back to normal "auto" pointerEvents for all overlays.

var ctx = document.createElement("canvas").getContext("2d");

$('#logo').on("mousedown", function(event) {

  // Get click coordinates
  var x = event.pageX - this.offsetLeft,
      y = event.pageY - this.offsetTop,
      w = ctx.canvas.width = this.width,
      h = ctx.canvas.height = this.height,
      alpha;

  // Draw image to canvas
  // and read Alpha channel value
  ctx.drawImage(this, 0, 0, w, h);
  alpha = ctx.getImageData(x, y, 1, 1).data[3]; // [0]R [1]G [2]B [3]A

  // If pixel is transparent, 
  // retrieve the element underneath and simulate its click event
  if( alpha===0 ) {
    this.style.pointerEvents = "none";
    $(document.elementFromPoint(event.clientX, event.clientY)).trigger("click");
    this.style.pointerEvents = "auto";
  } else {
    console.log("LOGO clicked!");
  }
});


$("#green").on("click", function(){
  console.log("Green image clicked!");
});
img{border:1px solid #000;}
img + img{position:absolute;top:0; left:0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="green" src="//placehold.it/200x140/cf5">
<img id="logo"  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJ4AAACeCAYAAADDhbN7AAAAGXRFWHRTb2Z0d2FyZQBB...
"

Answer №2

If you want to only capture click events on the opaque area of an image, a simple solution is to use a map in HTML along with some JavaScript:

<img src="https://i.sstatic.net/Ab6aW.jpg" alt="" usemap="#Map" />
<map name="Map" id="Map">
<area
  href="javascript:alert('You clicked on the image!')"
  shape="poly" 
  coords="193,148,50,193,254,292,461,191,302,141,332,99,285,27,220,16,170,89"
/>
</map>

(I found these coordinates using this helpful site.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Embedded script displayed as textual content

I have HTML elements that are stored as a string and inserted into a webpage using AJAX with the jQuery method replaceWith(). The string contains a <div> element and an inline <script> that operates on it. The jQuery command I am using looks so ...

Creating a new row does not result in the creation of a new span displaying the character count message

Every description field should have its own character counter, with different SpanIDs displayed in respective SpanIds for each new row. How can this be achieved? <div class="row"> <div class="col-s ...

After the page loads, the Facebook Like button causes my website content to shift downwards by 1 pixel

Why does the like button push down my website content by 1 pixel after loading? Any ideas on what might be causing this issue? Check out the website: See the problem in action here: ...

React Native / Redux - The "Cannot update during an existing state transition" error occurs when attempting to update

Currently working on an app using React Native and Redux, I've encountered a snag in the implementation process. An error message pops up saying setState cannot update during an existing state transition (such as within render or another componen ...

The placement of the React.js/Next.js Loader is incorrect on the page

While I was trying to display a Loader over everything during data fetching from my API, I encountered a situation where the Loader was not appearing at the expected top level but inside the page itself. Even though the HTML tree showed it at the top level ...

Leveraging CamanJS for canvas filtering

These are my HTML elements: <div class="wrapper"> <nav class="navbar navbar-transparent"> <div class="container-fluid"> <div class="navbar-header"> <span class="btn btn-white btn-file"> ...

Delete the div element upon clicking the .close button

Is there a way to remove the div that contains the .close link when the .close link is clicked? I attempted using $(this).closest('div').remove() but it didn't work as expected... $(".close").hide(); $(".delete-link").bind("click", function ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Utilize String to Set Cookies

My goal is to utilize requestjs for making requests and sharing cookies across various JavaScript files and servers. To achieve this, I have chosen to store the cookies in a database as a string and retrieve them when necessary. The string format aligns w ...

What is the best way to pass a function as a prop from a parent component to a child component and access it?

I am currently attempting to pass a function as a prop to a child component, DetailViewOfEntity, that is defined in the parent component, App.js. However, when I click on the button, I encounter an error stating that this.setState and obj.detailview are no ...

Patiently waiting for the component variable to be assigned through subscription

I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning ...

I'm experiencing difficulty in loading a static HTML page from the app file when using Node.js

I'm currently working on setting up a system where an HTML page is loaded upon request to the app. Although I've managed to get the HTML to load successfully using res.end('') within the server definition, I find this method to be messy ...

Encountering a CORS error while trying to fetch a YouTube page in React

Can someone help me extract the HTML markup of a YouTube video page? Below is the code I have so far: async function get_subtitles(video_id: string): Promise<string> { if (video_id.includes('https://') || video_id.includes('http:// ...

At what point does a dynamically loaded CSS file in the head section of a webpage actually

If the answer is already out there somewhere, I would really appreciate a link because I just can't seem to find it. When loading .php pages, I either include 'header.php' directly with <?php include 'header.php'; ?> or on ...

Button with opaque background over a see-through backdrop

I am having trouble making the button within a semi-transparent caption area over an image non-transparent. Any suggestions on how to achieve this? <div class="col-md-12 landing-container"> <img src="images/pig.jpg" class="main-imag ...

Getting the most out of jQuery DataTables column sizing

In my .NET web application, I am utilizing jQuery DataTables. I am wondering how to set a maximum width for only one specific column while allowing all other columns to be auto sized, as they currently are in my table. UPDATE The issue with the DataTable ...

What is the best way to configure my Express API endpoint so that it can generate customized responses based on the parameters in the URL?

Currently working on a react-admin project where I need to establish a connection with an express server using a data provider. Despite my efforts, I have been unable to implement sorting and pagination functionality. It seems like modifications are requi ...

"Angularjs tip: If the value of the href attribute is null, make sure

I am attempting to add a condition to either href or ng-href. The condition I want to apply is if email !== null. My current code appears as follows: <a ng-attr-href="{{email !== null}}" href="mailto:{{email | lowercase}}">{{email | lowercase | nu ...

Menu options are unresponsive to clicks in the dropdown

Need help fixing my dropdown menu issue. Whenever I hover over the dropdown, it disappears before I can click on any items. Here is a snippet of the code causing the problem: #navContainer { margin: 0; padding: 0; padding-top: 17px; width: 220 ...

Click on the navigation bar buttons to toggle between different divs and display multiple information boxes simultaneously

Here is the current code snippet... $("#contact").click(function() { if ( $( "#contact_div" ).length ) { $("#contact_div").remove(); } else { var html='<div id="contact_div" class="contact-info"><p>Contact info</p&g ...