Ad

Fabric JS Line From Point To Point

- 1 answer

I now have freedrawing with few different colors. I would like to free draw line parts instead of fully free draw. I need to mark water and gas lines on map with eg 6. lines that each starts on end of the last one.

function enableFreeDrawing() {
    removeEvents();
    canvas.isDrawingMode = true;
    canvas.freeDrawingBrush.color = e.target.value;
}

document.getElementById('colorpicker').addEventListener('click', function (e) {
    canvas.freeDrawingBrush.color = e.target.value;
    canvas.freeDrawingBrush.width = 2;
});

Please suggest me how to draw lines from each point to another with eg. 6 clicks, and finish it with enter or doubleclick

Ad

Answer

On a canvas element, I would create an indicative circle point on each click and connect the dots whenever a new point is created.

var canvas = new fabric.Canvas("canvas");
var waterPipePoints = [];
var waterPipeLines = [];

canvas.on("mouse:down", function(event) {
    var pointer = canvas.getPointer(event.e);
    var positionX = pointer.x;
    var positionY = pointer.y;

    // Add small circle as an indicative point
    var circlePoint = new fabric.Circle({
        radius: 5,
        fill: "blue",
        left: positionX,
        top: positionY,
        selectable: false,
        originX: "center",
        originY: "center",
        hoverCursor: "auto"
    });

    canvas.add(circlePoint);

    // Store the points to draw the lines
    waterPipePoints.push(circlePoint);
    console.log(waterPipePoints);
    if (waterPipePoints.length > 1) {
        // Just draw a line using the last two points, so we don't need to clear
        // and re-render all the lines
        var startPoint = waterPipePoints[waterPipePoints.length - 2];
        var endPoint = waterPipePoints[waterPipePoints.length - 1];

        var waterLine = new fabric.Line(
        [
            startPoint.get("left"),
            startPoint.get("top"),
            endPoint.get("left"),
            endPoint.get("top")
        ],
        {
            stroke: "blue",
            strokeWidth: 4,
            hasControls: false,
            hasBorders: false,
            selectable: false,
            lockMovementX: true,
            lockMovementY: true,
            hoverCursor: "default",
            originX: "center",
            originY: "center"
        }
        );

        waterPipeLines.push(waterLine);

        canvas.add(waterLine);
    }
});

canvas.renderAll();

Please check this example SandBox: https://codesandbox.io/s/stackoverflow-60753858-fabric-js-1720-26twl

Ad
source: stackoverflow.com
Ad