fabric.js: 如何填充徒手绘制形状的路径?
fabric.js: How to fill a free hand path to draw the shape?
在fabric.js中,我们可以自由绘制路径(例如http://fabricjs.com/freedrawing)。
不过,在一个HTML canvas 2d-context ctx中,我也可以画一条路径,然后调用
ctx.fill()
填充路径并从路径中填充形状。
示例代码:当鼠标向上移动时,路径被填充。
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);
}
}
fabricjs 也可能有类似的行为吗?
fabricjs好像只保存路径,不保存填充区域
谢谢,
彼得
在织物中绘图会生成一堆路径对象,您可以像大多数其他织物对象一样向它们添加填充。这是一个示例脚本,它会在鼠标松开时自动将每个创建的对象设置为蓝色背景:
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>
在fabric.js中,我们可以自由绘制路径(例如http://fabricjs.com/freedrawing)。
不过,在一个HTML canvas 2d-context ctx中,我也可以画一条路径,然后调用
ctx.fill()
填充路径并从路径中填充形状。
示例代码:当鼠标向上移动时,路径被填充。
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);
}
}
fabricjs 也可能有类似的行为吗?
fabricjs好像只保存路径,不保存填充区域
谢谢, 彼得
在织物中绘图会生成一堆路径对象,您可以像大多数其他织物对象一样向它们添加填充。这是一个示例脚本,它会在鼠标松开时自动将每个创建的对象设置为蓝色背景:
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>