2016-08-24 45 views
0
創建了一個形狀

我想要做什麼

我想畫一個自定義形狀(例如一個簡單的矩形),它針對每個邊緣不同的顏色。我可以用四條路徑完成它,它的功能就像一個魅力。但是,以這種方式,似乎我無法填補這個形狀。帆布 - 裝滿多個路徑

嘗試另一種方式,我可以繪製具有一條路徑的形狀並填充它,但在這種情況下,我無法使用不同顏色的邊緣,因爲最後的fillStyle將覆蓋以前的那些,即使我中風子路徑分別。

是否可以通過單獨着色子路徑或填充由多個路徑構成的形狀來混合兩者?

+0

多次抽獎呢?一個用於填充並且每個邊緣都獨立於筆劃(請記住爲每個新路徑調用beginPath) – Kaiido

+0

這並不容易。我有一步一步的執行。 – Nekomajin42

+1

那麼你可以更清楚,可能是一個示例代碼?當我讀到它時,你已經得到了點,讓我們說一個三角形p1,p2,p3。那麼爲什麼你不能'fillStyle = c0; beginPath方法();的moveTo(P1);了lineTo(P2); LT(P2); LT(P3);填(); FS = C1; BP(); MT(P1); LT(P2);行程(); FS = C2; BP(); MT(P2); LT(P3);行程(); FS = C3; BP(); MT(P3); LT(P1);中風();'? – Kaiido

回答

1

在畫布上使用不同的「圖層」,一個用於填充顏色形狀,另一個用於每個顏色路徑,z-index在畫布上不起作用,只要確保繪製底下的內容首先,只是將所有內容包裝在一個組<g>標記上,以便於操縱

+0

我使用''元素,而不是SVG。 – Nekomajin42

+0

不需要svg,你可以在canvas上重疊路徑 – StackOverMySoul

+0

https://jsfiddle.net/8pbq3gw8/ – StackOverMySoul

0

經過一些實驗後,我設法解決了我的問題。這不是一個理想的解決方案,因爲它有一些開銷,但它工作正常。

在繪圖操作開始時,我將目標座標存儲在一個數組中,並且一次又一次地繪製整個東西。每次運行都是一條新路。用.globalCompositeOperation = "destination-over"我可以在現有的下畫,所以每一行可以有不同的顏色。

在繪製操作結束時,數組包含形狀的所有座標,因此.fill()方法可以填充路徑。

我希望它可以幫助別人:

// get the canvas context 
 
var ctx = document.getElementById("myCanvas").getContext("2d"); 
 

 
// init shape array 
 
var shape = []; 
 
shape.push({ 
 
    x: 0, 
 
    y: 0 
 
}); // or any other starting point 
 

 
// let's try 
 
draw(20, 20); 
 
draw(40, 40); 
 
draw(60, 60); 
 

 
// this is how we draw 
 
function draw(x, y) { 
 
    // this is important 
 
    // see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation 
 
    ctx.globalCompositeOperation = "destination-over"; 
 

 
    // this is just to be more visible 
 
    ctx.lineWidth = 10; 
 

 
    // get a random color 
 
    ctx.strokeStyle = myRandomColor(); 
 

 
    // save target coordinates 
 
    shape.push({ 
 
    x: x, 
 
    y: y 
 
    }); 
 

 
    // reset the path 
 
    ctx.beginPath(); 
 

 
    // jump to the start point 
 
    ctx.moveTo(shape[0].x, shape[0].y); 
 

 
    // draw the whole stuff 
 
    for (var i = 0; i < shape.length; i++) { 
 
    ctx.lineTo(shape[i].x, shape[i].y); 
 
    } 
 
    ctx.stroke(); 
 
} 
 

 
function myRandomColor() { 
 
    var colors = ["red", "green", "blue", "yellow", "pink"]; 
 
    var rand = Math.round(Math.random() * 5); 
 
    return colors[rand]; 
 
}
<canvas id="myCanvas"></canvas>