Js:如何填充自由手路径来绘制形状? [英] fabric.js: How to fill a free hand path to draw the shape?

查看:17
本文介绍了Js:如何填充自由手路径来绘制形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Fabric.js中,我们可以绘制徒手路径(例如http://fabricjs.com/freedrawing)。

但是,在HTML画布2D上下文CTX中,我还可以绘制一个路径,然后调用

ctx.ill()

若要填充路径并在路径之外生成填充形状,请执行以下操作。

示例代码:当鼠标打开时,路径已填满。

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);
}

}

Fabric js是否也可能出现类似的行为?

Fabricjs似乎只保存路径,但不保存填充区域。

谢谢, 彼得

推荐答案

在Fabric中绘制会生成一组Path对象,您可以像大多数其他Fabric对象一样向它们添加填充。以下是一个示例脚本,它将在鼠标打开时将每个创建的对象自动设置为蓝色背景:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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>

这篇关于Js:如何填充自由手路径来绘制形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆