已编辑:通过使用鼠标事件的 clientX/Y 进行简化-删除需要获取元素偏移量
这是我想出的。基本上,通过使用纸张的客户端矩形和鼠标事件的 clientX/Y 将鼠标位置更正为相对于纸张。然后将校正后的位置与客户矩形的宽度/高度进行比较,然后按原始纸张尺寸计算结果:
var paper = Raphael(10, 50, 320, 200);
var rect = paper.rect(0, 0, 10, 10);
rect.attr('fill', 'green');
rect.mousedown(function (event, a, b) {
// get bounding rect of the paper
var bnds = event.target.getBoundingClientRect();
// adjust mouse x/y
var mx = event.clientX - bnds.left;
var my = event.clientY - bnds.top;
// divide x/y by the bounding w/h to get location %s and apply factor by actual paper w/h
var fx = mx/bnds.width * rect.attrs.width
var fy = my/bnds.height * rect.attrs.height
// cleanup output
fx = Number(fx).toPrecision(3);
fy = Number(fy).toPrecision(3);
$('#here').text('x: ' + fx + ', y: ' + fy);
});
paper.setViewBox(5, 5, 10, 10);
更新的小提琴链接在这里:http:
//jsfiddle.net/CEnBN/3/
鼠标按下功能的更紧凑版本:
rect.mousedown(function (event, a, b) {
var bnds = event.target.getBoundingClientRect();
var fx = (event.clientX - bnds.left)/bnds.width * rect.attrs.width
var fy = (event.clientY - bnds.top)/bnds.height * rect.attrs.height
$('#here').text('x: ' + fx + ', y: ' + fy);
});