In fabric.js, we can draw free hand paths (eg 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
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.