<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<link rel="stylesheet" href="css/shanxing.css">
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="tutorial" width="300" height="300"></canvas>
<script type="text/javascript">
function draw(){
var colorList=["rgb(98,160,255)","rgb(91,206,51)","rgb(244,185,115)","rgb(255,106,213)"];
var perList=[0.3,0.3,0.2,0.2];
var wordList=["1个月","3个月","6个月","12个月"]
var beginRadian=0;
var canvas = document.getElementById('tutorial');
if(!canvas.getContext) return;
var ctx = canvas.getContext("2d");
//开始代码
ctx.strokeStyle = "rgb(255,255,255)";
for(var i=0;i<4;i++){
ctx.fillStyle =colorList[i];
ctx.beginPath();
ctx.arc(75,50,50,beginRadian,beginRadian+2*perList[i]*Math.PI,false);
ctx.lineTo(75,50);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillRect(30*i,110,5,5);
ctx.fillText(wordList[i], 30*i+5, 115);
ctx.fillStyle ="rgb(255,255,255)";
ctx.fillText(perList[i]*100+'%', 75+25*Math.cos(beginRadian+perList[i]*Math.PI)-10, 50+25*Math.sin(beginRadian+perList[i]*Math.PI)+5);
beginRadian+=2*perList[i]*Math.PI;
}
}
draw();
</script>
</body>
</html>
今天有空实践写了个扇形图,有需要的借鉴。比较难一点的是如何在图形中画字,运用了极坐标系。还有画扇形的时候,为了简化代码,我使用了循环复用。其次如果想封装也没有问题!