I am currently working on a project where users tap on an irregularly shaped image in order to place a dot (Think of a dartboard or pin the tail on the donkey). I have no problems placing the dot on the canvas, however I run into problems where people tap outside the image (but still on the bounding-box of the image). Does anyone know how to filter out taps on the transparent part of an image? Here is my code:
<style>
#bodyImageFront {
display:block;
max-height: 75vh;
max-width: 90%;
height:auto;
width: auto;
margin-bottom: 10px;
z-index:1;
position:absolute;
}
canvas {
z-index:20;
}
</style>
<script>
var pointMap = [];
$(document).ready(function () {
drawCanvas();
});
$(window).resize(function () {
console.log("resize");
drawCanvas();
var tempArray = pointMap;
pointMap = [];
for (var i = 0; i < tempArray.length; i++) {
addPointToMap(tempArray[i]);
}
});
function drawCanvas() {
if (document.getElementById("bodyMapFrontCanvas")) {
document.getElementById("bodyMapFrontContainer").removeChild(document.getElementById("bodyMapFrontCanvas"));
}
var frontCanvas = document.createElement("canvas");
frontCanvas.setAttribute("id", "bodyMapFrontCanvas");
frontCanvas.setAttribute("width", document.getElementById("bodyImageFront").width);
frontCanvas.setAttribute("height", document.getElementById("bodyImageFront").height);
frontCanvas.setAttribute("style", "position:relative;");
frontCanvas.setAttribute("onclick", "addPointToMap(event, 'bodyMapFrontCanvas');");
document.getElementById('bodyMapFrontContainer').appendChild(frontCanvas);
}
function addPointToMap(point, canvasId) {
x = point.offsetX ? (point.offsetX) : event.pageX - document.getElementById(canvasId).offsetLeft;
y = point.offsetY ? (point.offsetY) : event.pageY - document.getElementById(canvasId).offsetTop;
var context = document.getElementById(canvasId).getContext("2d");
context.fillRect(x, y, 10, 10);
pointMap.
}
</script>
<html>
<form id="mainForm">
<div id="canvasContainer"></div>
<div class="col-xs-12 col-md-6" id="bodyMapFrontContainer">
<img src="~/Content/body.png" class="questionInputMethod" id="bodyImageFront" />
</div>
</form>
</html>
I apologize for the poor indentation Thanks in advance
Solution 1 : You have a complicated image with transparent border and don't want the transparent part to be clickable :
Draw the image into the canvas and use
getImageData(x,y,width,height)
to check if the pixel under the click is transparent.Solution 2 : You really only want to draw a simple shape like in the example you gave :
Draw this shape directly onto the canvas and use
isPointInPath()
to detect whether it should activate the click or not.Solution 3: Once again you only want a simple shape, and you don't really need
<canvas>
:Draw it with svg and add the event listener only to the svg element you want to listen to.