2012-09-26 22 views
2

enter image description here如何用一個HTML5畫布將一個圓分成三個相等的部分?

我怎樣才能用上圖中的HTML5 canvas 2D上下文API將一個圓分成三個相等的部分?

我試圖this

有人可以提出一個更好的辦法嗎?可能用百分比(或度數)代替硬編碼座標?

var can = document.getElementById('mycanvas'); 
var ctx = can.getContext('2d'); 

ctx.fillStyle = "#BD1981"; 
ctx.beginPath(); 
ctx.arc(200, 200, 150, 0, Math.PI*2, true); 
ctx.closePath(); 
ctx.fill(); 

ctx.strokeStyle = "#FFC8B2"; 
ctx.lineWidth = "2"; 
ctx.beginPath(); 
ctx.moveTo(200, 200); 
ctx.lineTo(100, 100); 
ctx.closePath(); 
ctx.stroke(); 

ctx.beginPath(); 
ctx.moveTo(200, 200); 
ctx.lineTo(350, 200); 
ctx.closePath(); 
ctx.stroke(); 

ctx.beginPath(); 
ctx.moveTo(200, 200); 
ctx.lineTo(100, 300); 
ctx.closePath(); 
ctx.stroke(); 
+0

什麼是 「百分比」 應該代表什麼? – phant0m

+0

像33%(100/3)或120度(360/3) –

+0

而如果我使用35%? – phant0m

回答

7

Here is a function (demo),允許你指定一個起點,長度和度的角度:

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(); 
} 
2

全部放在一起(使用@ phant0m的drawAngledLine):

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

function drawCircle(x, y, r) { 
    ctx.beginPath(); 
    ctx.arc(x, y, r, 0, 2 * Math.PI); 
    ctx.stroke(); 
} 

function drawAngledLine(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(); 
} 

drawCircle(140, 140, RADIUS); 
drawAngledLine(140, 140, RADIUS, 1 * (360/3)); 
drawAngledLine(140, 140, RADIUS, 2 * (360/3)); 
drawAngledLine(140, 140, RADIUS, 3 * (360/3)); 

在這裏演示:

0

我知道你可能有你的答案,但我發現韋恩的有用的jsfiddle所以我將我的貢獻,它可以讓你設置你想要分割的圓段的自定義數字。

http://jsfiddle.net/yorksea/3ef0y22c/2/

(也使用@ phant0m的drawAngledLine)

var c = document.getElementById("canvas"); 
 
var ctx = c.getContext("2d"); 
 
var RADIUS = 300; 
 
var num_sections = 19; //set this for number of divisions 
 

 
function drawCircle(x, y, r) { 
 
    ctx.beginPath(); 
 
    ctx.arc(x, y, r, 0, 2 * Math.PI); 
 
    ctx.stroke(); 
 
} 
 

 
function drawAngledLine(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(); 
 
} 
 

 
//draw circle outline 
 
drawCircle(320, 320, RADIUS); 
 

 
//loop the number of sections to draw each 
 
for (i = 1; i <= num_sections; i++) { 
 
    drawAngledLine(320, 320, RADIUS, i * (360/num_sections)); 
 
}
<canvas id="canvas" width="650" height="650"></canvas>

相關問題