canvas自定义数据圆环

原文: 本人掘金文章

关注公众号: 微信搜索 前端工具人 ; 收货更多的干货

我工作中常用可视化插件: 百度的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了,实现这个圆环也是比较粗糙;有的业务逻辑的绘制去掉了,没上传。

posted @ 2020-09-21 11:21  会写代码的赖先生  阅读(338)  评论(0编辑  收藏  举报