Haloor
Haloor

Reputation: 221

transforming mouse coordinates in CANVAS using fabric.js

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();
}

Upvotes: 0

Views: 1550

Answers (1)

BKR
BKR

Reputation: 443

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.

Upvotes: 1

Related Questions