[英]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 (ie not the screen coordinate). 我已经使用fabric.js设计了标尺,并且当用户将鼠标悬停在标尺的特定部分上时,我想在屏幕上打印标尺的X坐标(即不是屏幕坐标)。 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). 现在,标尺画布在相对于标尺的位置37处开始,在726处结束,但是标尺从1到4600(它将始终从1开始,但是标尺的长度可以更改)。 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();
}
Use the getPointer merthod on canvas Instance. 在画布实例上使用getPointer方法。 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. 在您的情况下,它应该是canvas.getPointer(options.e)
,它返回一个具有x和y属性的对象,这些属性表示相对于画布的指针坐标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.