利用canvas進行一個餅形圖的繪製,canvas餅形圖繪製

來源:互聯網
上載者:User

利用canvas進行一個餅形圖的繪製,canvas餅形圖繪製

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>繪製餅形圖。</title>
<style>
canvas{
border: 1px solid green;
}
</style>
</head>
<body>
<!-- 繪製餅形圖 -->
<canvas width="500" height="500" id="canvas"></canvas>
</body>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function toAngle(radian){
return radian*180/Math.PI;
}
function toRadian(angle){
return angle*Math.PI/180;
}
/*將餅狀圖畫出來*/
var colors = 'green,yellow,pink,blue,red,lightgreen,lightblue'.split(',');
var text = 'HTML5,Canvas,Javascript,Css3,Ajax,架構封裝,jQuery與移動Web'.split(',');
var x0 = canvas.width/2,
y0 = canvas.height/2,
radius = 100,
start = -5,
distance = 20,
padding = 5,
step = 360/colors.length;
for(var i = 0 ; i < colors.length ; i ++){
ctx.beginPath();
ctx.fillStyle = colors[i];
ctx.moveTo(x0,y0);
ctx.arc(x0,y0,radius,toRadian(start),toRadian(start+=step));
ctx.fill();
/*畫斜線*/
ctx.beginPath();
ctx.strokeStyle = colors[i];
var x1 = x0 + (radius+distance)*Math.cos(toRadian(( start-step/2 ))),
y1 = y0 + (radius+distance)*Math.sin(toRadian(( start-step/2 )));
ctx.moveTo(x0,y0);
ctx.lineTo(x1,y1);
ctx.stroke();
/*寫文字*/
ctx.beginPath();
ctx.fillStyle = colors[i];
var textX = x1,
textY = y1;
if(start-step/2 > 90 && start-step/2 < 270){
ctx.textAlign = 'right';
textX = textX - padding;
}else{
ctx.textAlign = 'left';
textX = textX + padding;
}
ctx.fillText(text[i],textX,textY-padding/2);
/*畫直線*/
ctx.beginPath();
ctx.moveTo(x1,y1);
//計算文字的寬度
var length = ctx.measureText( text[ i ] ).width
if(start-step/2 > 90 && start-step/2 < 270){
x1 += -2*padding-length;
}else{
x1 += 2*padding + length;
}
ctx.lineTo(x1,y1);
ctx.stroke();
/*畫餅形圖*/
/*ctx.beginPath();
ctx.fillStyle = colors[i];
ctx.moveTo(x0,y0);
ctx.arc(x0,y0,radius,toRadian(start),toRadian(start+=step));
ctx.fill();*/
}
</script>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.