zoukankan      html  css  js  c++  java
  • canvas自定义数据圆环

    原文: 本人掘金文章

    关注公众号: 微信搜索 web全栈进阶 ; 收货更多的干货

    我工作中常用可视化插件: 百度的echarts、mapv;阿里的antv系列;以及three.js;

    当插件有时满足不了我们相对应的需求(数据圆环)、UI又要求必须这样时, 这时就要考虑自定义了;

    一、效果图

    二、HTML

    <canvas id="canvas" width="250" height="170"></canvas>
    

    三、JS

    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    
    // 填充画布
    ctx.fillStyle= 'transparent';
    ctx.fillRect(0,0, 150, 150);
    
    ctx.beginPath();
    // 初始化画布起点
    ctx.translate(250/2, 170/2);
    // 起点
    ctx.moveTo(0,0);
    // 画大圆
    ctx.arc(0,0, 60,0,Math.PI*2,false);
    ctx.closePath();
    ctx.fillStyle='transparent';
    ctx.fill();
    
    // 动态环比
    let arr = ['0.85', '0.15']
    let beginDeg = Math.PI * 1.5
    let endDeg = Math.PI * 1.5
    arr.forEach((t, index) => {
      endDeg = beginDeg + (2 * Math.PI * t);
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.arc(0, 0, 60, beginDeg, endDeg, false);
      if (index < 1) beginDeg = endDeg
      ctx.closePath();
      ctx.fillStyle = index === 0 ? '#f00' : '#ff0';
      ctx.fill();
      
      // 使某部分圆环变小,且在最外边; 效果图黄色部分
      if (index === 1) {
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.arc(0,0,56,beginDeg, endDeg,false);
        ctx.closePath();
        ctx.fillStyle= '#000';
        ctx.fill();
      }
    })
    
    //变成圈图,中间加点东西
    ctx.beginPath();
    ctx.arc(0, 0, 50, 0,Math.PI * 2, true);
    ctx.closePath();
    ctx.fillStyle = "#000";
    ctx.fill();
    
    //绘制文字
    ctx.moveTo(0,0);//移动笔触到原点
    ctx.fillStyle = 'white';//文本颜色
    ctx.font="20px normal ";
    ctx.textAlign="center";//相对原点水平居中
    ctx.textBaseline="middle";//相对原点垂直居中
    ctx.fillText("88.8%",0,-8);
    
    ctx.moveTo(0,0);//移动笔触到原点
    ctx.fillStyle = 'white';//文本颜色
    ctx.font='15px normal ';//文本
    ctx.textAlign="center";//相对原点水平居中
    ctx.textBaseline="middle";//相对原点垂直居中
    ctx.fillText('离线率',0,15);//开始写字
    

    四、结语

    有段时间没有使用canvas了,实现这个圆环也是比较粗糙;有的业务逻辑的绘制去掉了,没上传。

  • 相关阅读:
    [WF4.0 实战] AutoResetEvent具体解释(线程独占訪问资源)
    linux下getrlimit与sysconf函数
    36.怎样使用定时任务
    1016. 部分A+B (15)
    找你妹+ipad+wifi,回顾那年的经典游戏
    Oracle 外键约束子表、父表
    字符串 上
    LeetCode103 BinaryTreeZigzagLevelOrderTraversal(二叉树Z形层次遍历) Java题解
    jquery ajax參数加点号状态200进error
    泛型数组随机排列工具类
  • 原文地址:https://www.cnblogs.com/ljx20180807/p/13704533.html
Copyright © 2011-2022 走看看