如何在Raphael的纸张坐标系中获得活动

时间:2013-03-06 20:12:51

标签: raphael

我想在Raphael的纸张坐标中获取鼠标事件的坐标。即使我使用了setViewBox,我也希望它们准确无误。

请参阅http://jsfiddle.net/CEnBN/

以下内容创建一个10x10绿色框然后放大 - 该视图的原点位于该框的中心。

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) {
    $('#here').text([a, b]);
    console.log(event);
});

paper.setViewBox(5, 5, 10, 10);

我希望获得反映其在框中位置的点击坐标。即。它们的范围应为([5-10],[5-10])。


注意:很久以后,我已经迁移到D3.js - 这通常让我更开心。

3 个答案:

答案 0 :(得分:1)

编辑:使用mouseX事件的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);
});

答案 1 :(得分:0)

您需要抵消结果,如下所示:

var posx, posy;

var paper = Raphael("canvas", 320, 200);

var rect = paper.rect(0, 0, 10, 10);
rect.attr('fill', 'green');

rect.mousedown(function (e, a, b) {
    posx = e.pageX - $(document).scrollLeft() - $('#canvas').offset().left;
    posy = e.pageY - $(document).scrollTop() - $('#canvas').offset().top;
    $('#here').text([posx, posy]);
    console.log(e);
});

paper.setViewBox(5, 5, 10, 10);

我为Raphaeljs添加了一个目标元素,看看this update to your jsfiddle

答案 2 :(得分:0)

gthmb的答案非常好,但遗漏了一个细节 - 矩形在纸上的位置。如果矩形位于(0,0)位置,则此版本仅起作用。要同时支持翻译的情况,请将矩形的位置添加到结果中:

function mouseEvent_handler(e) {
    var bnds = event.target.getBoundingClientRect();
    var bbox = this.getBBox();
    var fx = (event.clientX - bnds.left)/bnds.width * rect.attrs.width + bbox.x;
    var fy = (event.clientY - bnds.top)/bnds.height * rect.attrs.height + bbox.y;

    $('#here').text('x: ' + fx + ', y: ' + fy);
}

这里是小提琴的修改版本:http://jsfiddle.net/zJu8b/1/