I have a canvas which contains some rectangles (which are created by rotating the context etc.). There is an image which is loaded on to the canvas and then the rectangles map a certain area (for which the co-ordinates come from AJAX Service).
I need to know which rectangle the client has clicked. Sometimes it works when the canvas isn't transformed, but once I transform the canvas (by zooming or dragging), the mouse X Y position doesn't stay relative to the canvas.
My requirement is to show alert if the user clicks inside the rectangle. Even when zoomed or panned
Here is the JSFIDDLE:
https://jsfiddle.net/a5t0w1dj/2/
(See the red line from Minnesota to South Dakota)
Following is the code that generates my rectangle:
var rect = (function() {
// constructor
function rect(id, x, y, angle, width, height, fill, stroke, strokewidth) {
this.x = x;
this.y = y;
this.id = id;
this.width = width < 0 ? width * -1 : width;
this.height = height < 0 ? height * -1 : height;
this.fill = fill || "#ff0000";
this.stroke = stroke || "#00ff00";
this.strokewidth = strokewidth || 1;
this.angle = angle || 0;
this.redraw(this.x, this.y);
return (this);
}
rect.prototype.redraw = function(x, y) {
this.x = x || this.x;
this.y = y || this.y;
this.draw(this.stroke);
return (this);
}
//
rect.prototype.highlight = function(x, y) {
this.x = x || this.x;
this.y = y || this.y;
this.draw(this.ctx, "#00ffff");
return (this);
}
//
rect.prototype.draw = function(stroke) {
//ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.fillStyle = this.fill;
ctx.strokeStyle = stroke;
ctx.lineWidth = this.strokewidth;
ctx.rect(0, 0, this.width, this.height);
ctx.stroke();
ctx.fill();
ctx.closePath();
ctx.restore();
}
//
rect.prototype.isPointInside = function(x, y) {
console.log("X: " + x + ', Y: ' + y);
console.log(this.x + ', ' + (this.x + this.width) + ', ' + this.y + ', ' + (this.y + this.height));
return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height);
}
return rect;
})();
I have hit a dead end here, can anyone please help me out with this. Thanks alot.
EDIT
I have been trying different techniques, even tried the one in the comments but it didn't work.
All I need is a message on mouse click when the user clicks anywhere on the line