2017-04-17 18 views
1

我有一個問題globalCompositeOperation如何在畫布的元素上正確應用globalCompositeOperation?

我的目標是讓藍色元素僅在紅色元素內部顯示,並且根本不應該在紅色矩形外部可見(某種溢出隱藏效果)。另外,紅色和藍色都必須具有轉換能力(兩者均可編輯)。你可以看到,如果我在畫布上添加一個元素(黃色元素),藍色區域在黃色和藍色重疊的區域變得可見。

http://jsfiddle.net/redlive/q4bvu0tb/1/

var canvas = new fabric.Canvas('c'); 


var yellow = new fabric.Circle({ 
    top: 200, 
    left: 0, 
    radius: 100, 
    strokeDashArray: [5, 5], 
    stroke: 'black', 
    strokeWidth: 5, 
    fill: 'yellow' 
}); 
canvas.add(yellow); 


var red = new fabric.Rect({ 
    top: 0, 
    left: 0, 
    width: 300, 
    height: 300, 
    strokeDashArray: [5, 5], 
    stroke: 'black', 
    strokeWidth: 5, 
    fill: 'red', 
    rx: 40 
}); 
canvas.add(red); 


var blue = new fabric.Circle({ 
    top: 150, 
    left: 80, 
    radius: 100, 
    strokeDashArray: [5, 5], 
    stroke: 'black', 
    strokeWidth: 5, 
    fill: 'blue', 
    globalCompositeOperation: 'source-atop' 
}); 
canvas.add(blue); 



var green = new fabric.Circle({ 
    top: 0, 
    left: 0, 
    radius: 100, 
    strokeDashArray: [5, 5], 
    stroke: 'black', 
    strokeWidth: 5, 
    fill: 'green' 
}); 
canvas.add(green); 

強制性條件:

  • 保留在畫布上的元素的外觀。
  • 不修剪(因爲裁剪 不允許添加背景顏色和圖像在同一時間)

回答

1

這可能是使用下列步驟完成,能...

  • 刪除繪製blue元素之後繪製blue一個
  • 之前yellow元素設置yellow元素的globalCompositeOperationdestination-over並將其添加回

var canvas = new fabric.Canvas('c'); 
 

 
var yellow = new fabric.Circle({ 
 
    top: 200, 
 
    left: 0, 
 
    radius: 100, 
 
    strokeDashArray: [5, 5], 
 
    stroke: 'black', 
 
    strokeWidth: 5, 
 
    fill: 'yellow' 
 
}); 
 
canvas.add(yellow); 
 

 
var red = new fabric.Rect({ 
 
    top: 0, 
 
    left: 0, 
 
    width: 300, 
 
    height: 300, 
 
    strokeDashArray: [5, 5], 
 
    stroke: 'black', 
 
    strokeWidth: 5, 
 
    fill: 'red', 
 
    rx: 40 
 
}); 
 
canvas.add(red); 
 

 
canvas.remove(yellow); //remove yellow 
 

 
var blue = new fabric.Circle({ 
 
    top: 150, 
 
    left: 80, 
 
    radius: 100, 
 
    strokeDashArray: [5, 5], 
 
    stroke: 'black', 
 
    strokeWidth: 5, 
 
    fill: 'blue', 
 
    globalCompositeOperation: 'source-atop' 
 
}); 
 
canvas.add(blue); 
 

 
yellow.set({globalCompositeOperation: 'destination-over'}); //set gCO for yellow 
 
canvas.add(yellow); //add yellow back 
 

 
var green = new fabric.Circle({ 
 
    top: 0, 
 
    left: 0, 
 
    radius: 100, 
 
    strokeDashArray: [5, 5], 
 
    stroke: 'black', 
 
    strokeWidth: 5, 
 
    fill: 'green' 
 
}); 
 
canvas.add(green);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script> 
 
<canvas id="c" width="800" height="800"></canvas>

+0

感謝您發表評論......這樣它會,我知道......問題是,元素負載動態的畫布,我需要保持他們的外觀(Z-索引)。黃色必須在紅色區域之後。 –

+0

@Redlive ohk ..檢查更新的答案 –

+0

非常好...可能是一個潛在的解決方案,但是,使用Removing和Adding元素的這種操作會破壞動態元素渲染的條件,因此不會保留他們的排序... –