2015-10-13 162 views
7

我想繪製一條路徑,並將它用作我的畫布的遮罩。剪輯到繪製路徑

'use strict'; 

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

canvas.freeDrawingBrush = new fabric.PencilBrush(canvas); 
canvas.freeDrawingBrush.color = '#000'; 
canvas.freeDrawingBrush.width = 100; 

fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) { 

    canvas.add(img); 
    canvas.setWidth(img.getWidth()); 
    canvas.setHeight(img.getHeight()); 
    canvas.centerObject(img); 
    img.selectable = false; 
}); 

canvas.on('path:created', function(data) { 

    var path = data.path; 

    canvas.remove(path); 
    canvas.clipTo = function(context) { 
     path.render(context); 
    }; 

    canvas.isDrawingMode = false; 
    canvas.renderAll(); 
}); 

如何讓整個路徑成爲圖像的可見區域?

http://jsfiddle.net/db45yhpo/

編輯

這就是我想實現的,但使用FabricJS。

http://www.createjs.com/demos/easeljs/alphamaskreveal

+0

你想只使用路徑,而不是區域的路徑內,作爲面膜?確切地說, – approxiblue

+0

。例如,對於SprayBrush,我只想將紅色部分用作掩碼http://jsfiddle.net/db45yhpo/2/ –

回答

3

我有fabricjs沒有經驗,所以有可能是處理這個更好的方式,但我想:
重繪隱藏畫布上的路徑,
然後創建一個新fabric.Image( )
將其參數globalCompositeOperation設置爲`「destination-atop」,
在原始畫布上繪製它。

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

 
canvas.freeDrawingBrush = new fabric.PencilBrush(canvas); 
 
canvas.freeDrawingBrush.color = '#000'; 
 
canvas.freeDrawingBrush.width = 100; 
 

 
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) { 
 
    canvas.add(img); 
 
    canvas.setWidth(img.getWidth()); 
 
    canvas.setHeight(img.getHeight()); 
 
    canvas.centerObject(img); 
 
    img.selectable = false; 
 
}); 
 

 
canvas.on('path:created', function(data) { 
 
    var clipper = document.createElement('canvas'); 
 
    clipper.width = canvas.width; 
 
    clipper.height = canvas.height; 
 
    var ctx = clipper.getContext('2d'); 
 
    var path = data.path; 
 
    data.path.render(ctx); 
 
    canvas.remove(path); 
 
    canvas.isDrawingMode = false; 
 
    var oImg = new fabric.Image(clipper) 
 
    oImg.globalCompositeOperation = 'destination-atop'; 
 
    canvas.add(oImg); 
 
    canvas.renderAll(); 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script> 
 
<canvas id="c"></canvas>