2014-10-05 199 views
2

我想在FabricJS中創建一個效果,其中我添加到畫布中的某些文本的顏色由紋理決定。應該很容易,但是當我將紋理應用爲一種模式時,我無法制定出需要使其工作的縮放,旋轉等組合。在我看來,模式被應用於對象的「局部」,所以(0,0)是對象的左上角座標,而不是整個圖像的座標。FabricJS中的文本顏色疊加

所以,如果這裏是我的文字顏色紋理,

enter image description here

和我把一些文字中間,我想效果會是這樣的:

enter image description here

我已經用靜態畫布等嘗試了各種各樣的東西,但我已經走到了死衚衕。請有人可以幫忙嗎?這是我目前的嘗試:

var patternSourceCanvas = new fabric.StaticCanvas(); 

    oImg.setAngle(-angles[i]); 

    patternSourceCanvas.add(oImg); 

    var pattern = new fabric.Pattern({ 
     source: function() { 

     patternSourceCanvas.setDimensions({ 
      width: oImg.getWidth(), 
      height: oImg.getHeight() 
     }); 

     return patternSourceCanvas.getElement(); 
     }, 
     repeat: 'no-repeat' 
    }); 


    var text = new fabric.Text(entry, { 
     originX: 'center', 
     originY: 'center', 
     left: (coords[i][0] * bufWidth), 
     top: (coords[i][1] * bufHeight), 
     fill: pattern, 
     centeredRotation: true, 
     angle: angles[i], 
     fontFamily: 'Kapra', 
     fontSize: 42 
    }); 

巨大的感謝提前!

回答

2

我有這個想法,你可以使用fabricJs的掌握globalCompositeOperation屬性的對象

enter image description here

// clear canvas 
canvas.clear(); 

    var text = new fabric.Text('AAAAA', { 
     originX: 'center', 
     originY: 'center', 
     left:30, 
     top: 30, 
     fill: 'rgba(0,0,0,1)', 
     centeredRotation: true, 
     angle: 20, 
     fontSize: 100, 
    }); 
canvas.add(text); 
fabric.Image.fromURL('../assets/pug.jpg', function(oImg) { 
    oImg.globalCompositeOperation = 'source-atop'; 
    oImg.width = canvas.width; 
    oImg.heigth = canvas.height; 
    canvas.add(oImg); 
    var rect = new fabric.Rect({ 
    width: 200, 
    height: 200, 
    globalCompositeOperation: 'destination-over', 
    fill: 'black' 
    }); 
    canvas.add(rect); 
}); 

所以基本上你呈現任何顏色的文字,黑色取得效果。 然後,您將彩色圖像覆蓋在文字上,覆蓋所有畫布,並指定globalCompositeOperation = 'source-atop'

之後,您將在白色背景上顯示彩色文字。 現在畫一個黑色的背景作爲畫布,但指定globalCompositeOperation = 'destination-over'

所以你會做一些完全不同的東西,但它會工作。 可能需要調整,可能不適合您的需求。但它應該顯示你發佈的例子。

+0

我只是試圖導出SVG中的畫布,但不工作。 – AndreaBogazzi 2014-12-05 15:38:37