2016-08-26 9 views
1

fabric.js에서 자유로운 경로를 그릴 수 있습니다 (예 : http://fabricjs.com/freedrawing).fabric.js : 모양을 그리기 위해 자유로운 손 모양을 채우는 방법은 무엇입니까?

그러나, HTML 캔버스 2D 컨텍스트 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는 경로 만 저장하는 것으로 보이지만 채워진 영역은 저장하지 않는 것 같습니다.

덕분에, 피터

답변

2

그리기 직물에 경로 객체의 무리를 생성하고 당신은 대부분의 다른 직물 객체처럼에 채우기를 추가 할 수 있습니다.

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>

: 여기에 자동차까지 마우스 파란색 배경에 작성된 각 객체를 설정합니다 예를 들어 스크립트입니다