Reputation: 434
Like the title suggests, I'd like to know if a user is clicking on the non-transparent part of a png.
Further - imagine there are several layers of pngs that are layered ontop of each other. Same size, but for each layer, the non-transparent part gets smaller and smaller. I'd like to be able to identify which of the pngs are being clicked by identifying which non-transparent part the user clicks on.
Upvotes: 2
Views: 357
Reputation: 488
Mixing and matching the answers and comments above:
Attach a click handler for each png you've rendered. On click, the event will propagate from the top-most png of the stack (the first png the click "meets"), all the way to the bottom-most (the first one rendered).
The handler will execute the same logic for each png (you may reuse the same function):
If the png didn't meet your criteria, allow the event to keep propagating.
Upvotes: 1
Reputation: 19493
Let's try using a canvas. Thanks to @Yogi from the comments.
var url = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/420px-PNG_transparency_demonstration_1.png";
var image = new Image();
image.onload = function() {
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
canvas.addEventListener('mousedown', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
var data = context.getImageData(cx, cy, 1, 1).data;
console.log(""+data)
})
}
image.crossOrigin = "anonymous"
image.src = url;
<body>
click and get color in console.<br>
</body>
Upvotes: 3