I have the following PNG
image with transparency:
I would like to make a button in HTML
& CSS
that uses the alpha
channel as a mask, so that it only works if the users clicks in the pink area.
Is that possible? How can it be implemented?
I have the following PNG
image with transparency:
I would like to make a button in HTML
& CSS
that uses the alpha
channel as a mask, so that it only works if the users clicks in the pink area.
Is that possible? How can it be implemented?
You might want to check out image-map HTML map Tag
You need to draw your image into a canvas
to get the pixel values and check the alpha channel value:
const messageBox = document.getElementById('messageBox');
const imageButton = document.getElementById('imageButton');
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const width = imageButton.width;
const height = imageButton.height;
canvas.width = width;
canvas.height = height;
context.drawImage(imageButton, 0, 0, width, height);
imageButton.onclick = function(e) {
const alpha = context.getImageData(e.offsetX, e.offsetY, 1, 1).data[3];
switch (alpha) {
case 255:
messageBox.innerText = "Inside clicked";
break;
case 0:
messageBox.innerText = "Outside clicked";
// Here you could do e.preventDefault(); if this is a form submit event or something like that.
break;
default:
messageBox.innerText = "Border clicked.";
// Decide how to handle clicks in the border or change the switch for an if and define a range of valid and invalid values for the alpha channel.
break;
}
};
#imageButton {
box-shadow: inset 0 0 0 1px rgba(255, 0, 0, .5);
cursor: pointer;
width: 100px;
}
<img id="imageButton" src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" />
<div id="messageBox"></div>
Note I'm using a small data URI instead of your image to avoid Cross-Origin
issues or an answer that is larger than allowed.