使用 fabricjs 模拟自由绘图

2022-01-17 00:00:00 javascript html5-canvas fabricjs

我正在开发具有白板的应用程序.白板应该像 idroo.com 一样工作.一个用户正在绘制一些其他用户应该能够在他的浏览器上实时看到的东西.我使用fabricjs 作为画布包装器,它有我需要的一切.但我无法在画布上模拟自由绘图.我将鼠标位置和画笔选项发送到远程客户端,并尝试通过触发鼠标移动事件来呈现它们.但它不起作用.如果有人有类似的问题,你能帮忙吗?

I am developing application which has whiteboard. Whiteboard should work like idroo.com. One user is drawing something another user should be able to see it on his browser in real time. I use fabricjs as canvas wrapper and it has everithing I need. But I can't emulate free drawing on canvas. I send mouse position and brush options to remote client and try to render them by firing mouse move events. But it don't work. If some body has simialiar problem can you please help?

canvasContainer.on('mousemove', function (e) {      
    var left = canvasContainer.offset().left;
    var top = canvasContainer.offset().top;
    var x = e.pageX - left;
    var y = e.pageY - top;         
    //Send data to remote browser by socket.io or signalr
    //I need to draw on remote browser by these x and y coordinates.
    updateCursor(_connections, x, y);
});

推荐答案

你可以这样做:

var brush = new fabric.PencilBrush(canvas);
var points = [[10,10], [20,20], [25,70],[100,300]];

brush.onMouseDown({x:points[0][0], y:points[0][1]});
for(var i=1;i<points.length;i++) {
  brush.onMouseMove({x:points[i][0], y:points[i][1]});
}

在此处查看插件:https://plnkr.co/edit/V1c1xkB29tgB2ha99CRQ?p=preview

您可以简化计算 x 和坐标的代码,并像这样:

You can simplify your code for calculating x and coordinates and do it like this:

var point = canvas.getPointer(e);

相关文章