首页 > 其他 > 详细

canvas自定义数据圆环

时间:2020-09-21 12:46:27      阅读:43      评论:0      收藏:0      [点我收藏+]

原文: 本人掘金文章

关注公众号: 微信搜索 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了,实现这个圆环也是比较粗糙;有的业务逻辑的绘制去掉了,没上传。

canvas自定义数据圆环

原文:https://www.cnblogs.com/ljx20180807/p/13704533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!