JS Code -
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var BB=canvas.getBoundingClientRect();
var offsetX = BB.left;
var offsetY = BB.top;
var mx;
var my;
var texts = [];
var images = [];
var dragF = -1;
var mode = "none";
function print(log) {
console.log(log)
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(const { text, x, y, width, height } of texts) {
ctx.fillText(text, x, y);
// trace
ctx.strokeRect(x, y, width, height);
}
}
function addNewText(string_text, arrayname) {
var y = texts.length * 20 + 20;
var text = {
text: string_text,
x: 20,
y: y,
name: arrayname
};
ctx.font = "32px verdana";
ctx.textBaseline = "top";
text.width = ctx.measureText(text.text).width;
text.height = 32;
texts.push(text);
draw();
}
function hitDrag(x,y,textIndex) {
var r=texts[textIndex];
return (x>r.x && x<r.x+r.width && y>r.y && y<r.y+r.height);
}
function myDown(e) {
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
for(var i=0;i<texts.length;i++){
if(hitDrag(mx,my,i)){
print("found");
dragF = i;
}
}
}
$("#canvas").mousedown(function(e) {
myDown(e);
});
addNewText("Hello world", "text 1");
So I followed @Kaiido advice with the BBox and I changed textBaseline to "top". Which fits perfectly. Now when I run his code snipper under my help forum, it seems to work and print "found" (which shows it works). When I run it, it doesn't seem to work. What could be the reason for this.
His Code working: https://gyazo.com/511bf35523fcb3ea8a26c2b088530f99
My coding not working: https://gyazo.com/743c38f6a33a7f1f4513bac361c23588
HTML Code -
<div id="middle_container">
<div class="center_container">
<canvas id="canvas"></canvas>
</div>
</div>
CSS Code -
#canvas {
height: 667px;
width: 800px;
touch-action: auto;
cursor: inherit;
visibility: visible;
border: 1px solid grey;
}