transforming mouse coordinates in CANVAS using fabric.js

蓝咒 提交于 2019-12-14 04:08:34

问题


I have designed a ruler using fabric.js and when the user mouses over the specific part of the ruler I want to print to the screen the X-coordinate of the ruler (i.e. not the screen coordinate). Right now the ruler canvas starts at position 37 and ends at 726 relative to the ruler, but the ruler goes from 1 to 4600 (it will always start at 1 but the length of the ruler can change). How to transform the mouse coordinates to accurately reflect it's position on the ruler? Here is the code:

var canvas = new fabric.Canvas('canvas');

line_length = input_len;

adjusted_length = (line_length / 666) * 100;

canvas.add(new fabric.Line([0, 0, adjusted_length, 0], {
    left: 30,
    top: 0,
    stroke: '#d89300',
    strokeWidth: 3
}));

$('#canvas_container').css('overflow-x', 'scroll');
$('#canvas_container').css('overflow-y', 'hidden');

drawRuler();


function drawRuler() {
    $("#ruler[data-items]").val(line_length / 200);

    $("#ruler[data-items]").each(function () {
        var ruler = $(this).empty(),
            len = Number($("#ruler[data-items]").val()) || 0,
            item = $(document.createElement("li")),
            i;
        ruler.append(item.clone().text(1));
        for (i = 1; i < len; i++) {
            ruler.append(item.clone().text(i * 200));
        }
        ruler.append(item.clone().text(i * 200));
    });
}


canvas.add(new fabric.Text('X-cord', {
    fontStyle: 'italic',
    fontFamily: 'Hoefler Text',
    fontSize: 12,
    left: 0,
    top: 0,
    hasControls: false,
    selectable: false
}));

canvas.on('mouse:move', function (options) {
    getMouse(options); 
});


function getMouse(options) {
    canvas.getObjects('text')[0].text =
        "X-coords: " + options.e.clientX  ; //+ " Y: " + options.e.clientY;
    canvas.renderAll();
}

回答1:


Use the getPointer merthod on canvas Instance. In your case it should be canvas.getPointer(options.e)which returns an object with x and y properties which represent pointer coordinates relative to canvas.



来源:https://stackoverflow.com/questions/32868707/transforming-mouse-coordinates-in-canvas-using-fabric-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!