JSFiddle - React, Tailwind, and code Playground
HTML
<div id="main">
<img id="myimg" src="http://www.psypress.co.uk/mather/resources/jpg/Image9_4.jpg">
<svg id="myspace" height="500" width="500">
<rect id="myrect" x="50" y="14" width="200" height="174" style="fill-opacity:0"/>
</svg>
</div>
CSS
#main img {
position: absolute;
}
#main svg {
position: absolute;
border: 1px solid blue;
}
JavaScript
var noOfLines = -1;
$("#myspace").data("draw_mode", false);
var createline = function(id,x1,y1,x2,y2,color,w) {
var aLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
aLine.setAttribute('id', id);
aLine.setAttribute('x1', x1);
aLine.setAttribute('y1', y1);
aLine.setAttribute('x2', x2);
aLine.setAttribute('y2', y2);
aLine.setAttribute('stroke', color);
aLine.setAttribute('stroke-width', w);
return aLine;
}
var draw = function(e) {
console.debug("draw (" + e.pageX + "," + e.pageY + ")");
var draw_start = $("#myspace").data("draw_start");
var myline = $("#myline"+noOfLines)[0];
myline.setAttribute("x1", draw_start.x);
myline.setAttribute("y1", draw_start.y);
myline.setAttribute("x2", e.pageX);
myline.setAttribute("y2", e.pageY);
};
var penup = function(e) {
$("#myspace").data("draw_mode", false);
console.debug("pen up = " + $("#myspace").data("draw_mode"));
$("#myspace").off("mousemove", draw);
if ($("#myspace")[0].checkIntersection($("#myline"+noOfLines)[0], $("#myrect")[0].getBBox())) alert("Intersection Occurs");
};
var pendown = function(e) {
$("#myspace").data("draw_mode", true);
console.debug("pen down = " + $("#myspace").data("draw_mode"));
$("#myspace")[0].appendChild(createline('myline'+(++noOfLines),0,0,0,0,"rgb(255,0,0)",2));
$("#myspace").data("draw_start", { "x" : e.pageX, "y" : e.pageY });
$("#myspace").on("mousemove", draw);
};
$("#myspace").on("mouseup", penup);
//$("#myspace").on("mouseleave", penup);
$("#myspace").on("mousedown", pendown);
$("#myspace").css("width", $("#myimg").width());
$("#myspace").css("height", $("#myimg").height());