zoukankan      html  css  js  c++  java
  • 使用canvas绘制饼状图

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <body>
    <div id="container">
    <canvas id="cavsElem">
    你的浏览器不支持canvas,请升级浏览器
    </canvas>
    </div>
    <script>
    (function(){
    var canvas=document.querySelector('#cavsElem');
    var ctx=canvas.getContext('2d');
    canvas.width=600;
    canvas.height=600;
    canvas.strokeStyle='1px solid #000';
    var data = [{
    "value": .2,
    "color": "red",
    "title": "应届生"
    },{
    "value": .3,
    "color": "blue",
    "title": "社会招生"
    },{
    "value": .4,
    "color": "green",
    "title": "老学员推荐"
    },{
    "value": .1,
    "color": "#ccc",
    "title": "公开课"
    }];
    var tempAngle=-90;
    for(var i=0;i<data.length;i++){
    x0=400;
    y0=400;
    // 设置饼图的半径
    radius=200;
    // 每次循环开始一个新路径
    ctx.beginPath();
    // 将画笔移动到起始位置
    ctx.moveTo(x0,y0);
    // 每个扇形的角度
    var angle=data[i].value*360;
    ctx.fillStyle=data[i].color;
    // 将角度转化为弧度不,弧度rad=angle*Math.PI/180;
    var startAngle=tempAngle*Math.PI/180;
    var endAngle=(tempAngle+angle)*Math.PI/180;
    // 绘制
    ctx.arc(x0,y0,radius,startAngle,endAngle);
    var x,y;
    // 绘制文字的内容
    var txt=data[i].value*100+'%';
    // 文字的位置在每个扇形的中间
    var txtAngle=tempAngle+1/2*angle;
    x=x0+Math.cos(txtAngle*Math.PI/180)*(radius+20);
    y=y0+Math.sin(txtAngle*Math.PI/180)*(radius+20);
    // 设置文字的对齐方式ctx.textAlign:end是文字的尾部与线对齐
    if(txtAngle>90&&txtAngle<270){
    ctx.textAlign='end';
    }
    ctx.fillText(txt,x,y);
    ctx.fill();
    tempAngle+=angle;
    }
    }())
    </script>
    </body>
    </html>
  • 相关阅读:
    block、inline、inline-block
    js 的复制和引用 (传值和传址)
    俄罗斯方块和作品集
    js 连续赋值。。理解不了,先占坑
    8.7 jquery-dom manipulation
    08.04 对象构造方法
    对象的基本操作
    08.03 js _oop
    08.02 对象
    The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
  • 原文地址:https://www.cnblogs.com/yangguoe/p/7903272.html
Copyright © 2011-2022 走看看