Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fabric.js: How to fill a free hand path to draw the shape?

In fabric.js, we can draw free hand paths (e.g. http://fabricjs.com/freedrawing).

However, in a HTML canvas 2d-context ctx, I can also draw a path and then call

ctx.fill()

to fill the path and make a filled shape out of the path.

example code: when ever the mouse goes up, the path is filled.

function draw() {

ctx.lineCap = "round";
ctx.globalAlpha = 1;

var x = null;
var y = null;

canvas.onmousedown = function (e) {

    // begin a new path
    ctx.beginPath();

    // move to mouse cursor coordinates
    var rect = canvas.getBoundingClientRect();
    x = e.clientX - rect.left;
    y = e.clientY - rect.top;
    ctx.moveTo(x, y);

    // draw a dot
    ctx.lineTo(x+0.4, y+0.4);
    ctx.stroke();
};

canvas.onmouseup = function (e) {
    x = null;
    y = null;
    ctx.fill();
};

canvas.onmousemove = function (e) {
    if (x === null || y === null) {
        return;
    }
    var rect = canvas.getBoundingClientRect();
    x = e.clientX - rect.left;
    y = e.clientY - rect.top;
    ctx.lineTo(x, y);
    ctx.stroke();
    ctx.moveTo(x, y);
}

}

Is a similar behavior also possible with fabricjs?

fabricjs seems to only save the path, but not the filled area.

Thanks, Peter

like image 804
Peter Avatar asked Oct 22 '25 06:10

Peter


1 Answers

Drawing in fabric generates a bunch of path objects and you can add a fill to them just like most other fabric objects. Here is an example script that will auto set each created object to a blue background on mouse up:

var canvas = new fabric.Canvas('c', {
    isDrawingMode: true
 });

canvas.on('mouse:up', function() {
  canvas.getObjects().forEach(o => {
    o.fill = 'blue'
  });
  canvas.renderAll();
})
canvas {
    border: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.js"></script>

<canvas id="c" width="600" height="600"></canvas>
like image 162
StefanHayden Avatar answered Oct 23 '25 18:10

StefanHayden