2016-08-01 31 views
2

可以根據輸入在圓內創建分段。我試圖通過例如創建的段來表示在圓的形式的分數值: -如何在使用HTML5和CSS3的圓中創建分段

有一個div

<div class="circle"> 
</div> 

    circle has a width of 150px & height as well now with a border radius of 50%; 

我想利用分子的輸入值和分母顯示的數目在圈內的div

段例如這樣

enter image description here

+0

你想用div和CSS做這個嗎?或者你會看着畫在畫布上? –

+0

如果你是一些古怪的CSS,並不需要支持太多的傳統瀏覽器 - https://www.smashingmagazine.com/2015/07/designing-simple-pie-charts-with-css/ – dmoo

+0

@NicholasRobinson它沒有關係,但在輸入的基礎上,我想開發一些像這樣的東西在圖片中給出 –

回答

0

由於您將要處理可能複雜的角度,我建議您使用canvas。這裏是你如何能達到你所期待的一個例子:

//Getting the context for the canvas 
 
var canvas = document.getElementById('fraction'); 
 
var context = canvas.getContext('2d'); 
 

 
var x = 80; // X coordinate for the position of the segment 
 
var y = 80; // Y coordinate for the position of the segment 
 
var radius = 75; // Radius of the circle 
 

 
// This is what you will be changing 
 
// Maybe get these values from a function that pulls the numbers from an input box 
 
var numerator = 1; 
 
var denominator = 4; 
 
var fraction = numerator/denominator; // The angle that will be drawn 
 

 
// For plotting the segments 
 
var startAngle = Math.PI; 
 
var endAngle = (1 + (2 * fraction)) * startAngle; 
 

 
// If the circle is draw clockwise or anti-clockwise 
 
// Setting this to true will draw the inverse of the angle 
 
var drawClockwise = false; 
 

 
// Drawing the segment 
 
context.beginPath(); 
 
context.arc(x, y, radius, startAngle, endAngle, drawClockwise); 
 
context.lineTo(x, y); 
 
context.closePath(); 
 
context.fillStyle = 'yellow'; 
 
context.fill(); 
 

 
//***************** Edit ******************* 
 

 
// This will add the circle outline around the segment 
 
context.beginPath(); 
 
context.arc(x, y, radius, 0, Math.PI * 2, drawClockwise); 
 
context.closePath(); 
 
context.strokeStyle = '#000'; 
 
context.stroke();
<div> 
 
    <canvas id="fraction" width="200" height="200"></canvas> 
 
</div>

在上面的代碼,你可以用變量玩,但你會有興趣的主要因素是numerator,denominatorfraction。這些組成了你在上面提到的分數,並用於繪製正確的分段。

你也可以玩其他變量來改變形狀的大小和位置,它的繪製方向。你並不僅限於這些,還有很多其他的東西可以改變!

Here是畫圓和段到畫布上的一個例子,是here的一例如何設置和改變形狀的顏色和輪廓和here是介紹在一般以帆布。

我希望這有助於!

祝你好運:)