我正在尝试编写一个简单的java脚本程序来标记图像上的矩形。单击按钮添加矩形,然后单击左上角和右下角,程序应将矩形标记为红色。我正在使用jquery直接javascript。
除非矩形的左上角或右下角位于另一个矩形内,否则一切都会起作用,当处理点击事件时,x和y不正确。
我一直试图解决这个问题几个小时,谷歌没有帮助。我特意试过:
我创建了一个jsfiddle with an example that shows the problem。但是如果你不想点击它,这是我的JS代码:
var rects = [{x1: 708, y1: 246, x2: 738, y2: 277},
{x1: 442, y1: 239, x2: 474, y2: 271},
{x1: 676, y1: 242, x2: 703, y2: 270}];
var $container = $("#container");
var click_count = 0;
var added_rects = 0;
var waiting_for_clicks = false;
var new_rects = [];
var current_rect = {};
var add_rect = function(color, rect) {
$('<div class="child"/>')
.appendTo($container)
.css("left", rect.x1 + "px")
.css("top", rect.y1 + "px")
.css("width", (rect.x2-rect.x1)+"px")
.css("height", (rect.y2-rect.y1)+"px")
.css("border", "1px solid " + color);
};
var remove_last_rect = function() {
if (new_rects.length > 0) {
$container.children('div:last-child').remove();
new_rects.pop();
}
}
_.map(rects, _.partial(add_rect, 'red'));
var listen_for_rect = function() {
click_count = 0;
waiting_for_clicks = true;
current_rect = {x1: -1, y1: -1, x2: -1, y2: -1};
$('#add-rect').attr('disabled', 'disabled');
$('#remove-rect').attr('disabled', 'disabled');
};
var stop_listening_for_rects = function() {
waiting_for_clicks = false;
$("#add-rect").removeAttr('disabled');
$('#remove-rect').removeAttr('disabled');
add_rect('red', current_rect);
new_rects.push(current_rect);
}
$('#add-rect').click(function(e) {
e.preventDefault();
listen_for_rect();
});
$('#remove-rect').click(function(e) {
remove_last_rect();
if (new_rects.length == 0) $(this).attr('disabled', 'disabled');
});
var click_event = function(e) {
e.preventDefault();
if (waiting_for_clicks) {
click_count++;
var offset = $(this).offset();
var x = e.pageX-offset.left;
var y = e.pageY-offset.top;
console.log(x);
console.log(y);
if (click_count == 1) {
current_rect.x1 = x;
current_rect.y1 = y;
} else if (click_count == 2) {
current_rect.x2 = x;
current_rect.y2 = y;
stop_listening_for_rects();
}
}
};
$container.on('click', '.child', click_event);
$('img').click(click_event);
// console.log($('.child'));
答案 0 :(得分:3)
如果单击矩形内部,则x和y坐标
原因是,$(this).offset()返回您单击的元素的偏移量,而不是图像的偏移量,因此当您在rect内部单击时,它将返回rect的偏移量。
在click_event = function(e) {
:
var offset = $("img").offset();