2012-12-11 31 views
3

我試圖創建一個等分爲五個部分的環。我的方法可能是非正統的,因爲我是JS/JQuery的新手。 下面是我的代碼:我試圖使用ctx.clip如何在畫布中剪下戒指?

var c=document.getElementById("c"); 
var ctx=c.getContext("2d"); 

ctx.beginPath(); 
ctx.arc(430,430,300,0,2*Math.PI,true);//x-y-r-angle-PI-rotation(clockwise vs anti// 
ctx.closePath(); 
ctx.strokeStyle="#000"; 
ctx.stroke(); 

ctx.save(); 
ctx.beginPath(); 
ctx.arc(430,430,200,0,2*Math.PI); 
ctx.closePath(); 
ctx.strokeStyle="#000"; 
ctx.stroke(); 
ctx.clip(); 


var drawAngledLine = function(x, y, length, angle) { 
    var radians = angle/180 * Math.PI; 
    var endX = x + length * Math.cos(radians); 
    var endY = y - length * Math.sin(radians); 

    ctx.beginPath(); 
    ctx.moveTo(x, y) 
    ctx.lineTo(endX, endY); 
    ctx.closePath(); 
    ctx.stroke(); 
} 
ctx.strokeStyle = "#000"; 
ctx.lineWidth = "1"; 

drawAngledLine(430, 430, 300, -90); 
drawAngledLine(430, 430, 300, -162); 
drawAngledLine(430, 430, 300, -234); 
drawAngledLine(430, 430, 300, -306); 
drawAngledLine(430, 430, 300, -18); 

ctx.restore(); 
ctx.beginPath(); 
ctx.arc(430,430,200,0,2*Math.PI,true); 
ctx.strokeStyle="#000"; 
ctx.stroke(); 

(); 但它剪輯線的內部,我想它掩蓋內部,只顯示內部圈和外部圈之間的連接線。這很難解釋沒有圖像...

請有人可以幫忙。 提前歡呼。

回答

3

您可以通過幾種方法來實現。首先用切片繪製圓,然後在圓上繪製一個與背景相同的圓,使其看起來像一個圓環而不是一個整圓。另一種方式與上述相同,只不過您將畫布全局組合更改爲destination-out,這是畫布中的實際孔,將圓的那部分刪除。

Live Demo

var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext("2d"); 

    canvas.width = canvas.height = 256; 

    function toRadians(deg) { 
     return deg * Math.PI/180 
    } 


    slicedRing(128,128,5,50,20); 

    function slicedRing(x,y,sect,r,w){ 
     var slice = 360/sect; 

     ctx.fillStyle = "rgb(255,0,0)"; 
     ctx.strokeStyle = "#fff"; 

     for(var i = 0; i < sect; i++){ 
      ctx.beginPath(); 
      ctx.moveTo(x,y); 
      ctx.arc(x,y,50,toRadians(slice*i),toRadians((slice*i)+slice)); 
      ctx.fill(); 
      ctx.lineTo(x,y); 
      ctx.stroke(); 
      ctx.closePath(); 
     } 

     // either change this to the background color, or use the global composition 
     ctx.globalCompositeOperation = "destination-out"; 
     ctx.beginPath(); 
     ctx.moveTo(x,y); 
     ctx.arc(x,y,w,0,Math.PI*2); 
     ctx.fill(); 
     ctx.closePath(); 

     // if using the global composition method, make sure to change it back to default. 
     ctx.globalCompositeOperation = "source-over"; 
    } 
+1

Loktar IZ塔bezt –