简易的半环形图表

2020-02-26  本文已影响0人  LElysion

前言

最近公司美术想要一个半环形的图表, 奈何百度了没看到能用的, 便是决定自己手写一下了, 虽然并非通用配置图表, 但是基本的canvas思想应该是有了, 便是给各位用作参考

实现效果

微信截图_20200226110143.png

完整代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * { padding: 0; margin: 0; }
    .canvas { margin: 15px auto; display: block; }
  </style>
</head>

<body>
    <div id="dom"></div>
</body>
<script>
  drawRing({now: 588, total: 630, id: 'dom'});
  function drawRing({
    now, total, id
  }) {
    // 校验数据
    if(now > total) throw new Error(`当前值now:${now}不可大于总数total:${total}`);
    // 创建canvas dom
    let canvas = document.createElement('canvas');
    let dom = document.getElementById(id);
    canvas.style.margin = '15px auto';
    canvas.style.display = 'block';
    if(!dom) throw new Error(`请检查你的id${id}是否正确,该方法使用document.getElementById获取dom`);
    dom.appendChild(canvas);
    let color1 = '#A8D279';
    let color2 = '#FFD098';
    let fontSize = 14;
    let percentage = now / total;
    let text1 = '已上报' + now + '人';
    let text2 = '未上报' + total + '人';
    let w_width = window.innerWidth;
    // let canvas = document.getElementById('canvas');
    canvas.width = w_width * 0.6;
    canvas.height = w_width * 0.6;
    let ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.strokeStyle = color1;
    ctx.lineWidth = 20;
    let x = canvas.width / 2;
    let y = canvas.width / 2;
    let radius = canvas.width / 2 - 20;
    let startAngle = 0;
    let endAngle1 = Math.PI;
    let anticlockWise = true;
    // 绘制第一个半圆
    ctx.arc(x, y, radius, startAngle, endAngle1, true);
    ctx.stroke();
    // 绘制第二个半圆
    ctx.beginPath();
    ctx.strokeStyle = color2;
    ctx.lineWidth = 20;
    let endAngle2 = (Math.PI / 180) * (180 + (percentage * 180));
    ctx.arc(x, y, radius, startAngle, endAngle2, true);
    ctx.stroke();
    ctx.save();

    // 绘制文字
    ctx.font = fontSize + 'px Arial';
    let text1_width = ctx.measureText(text1).width;
    // ctx.textAlign = 'center';
    ctx.fillText(text1, (canvas.width - text1_width) / 2 + 14, y - 25);
    ctx.save();
    ctx.font = fontSize + 'px Arial';
    let text2_width = ctx.measureText(text2).width;
    // ctx.textAlign = 'center';
    ctx.fillText(text2, (canvas.width - text2_width) / 2 + 14, y - 5);
    ctx.save();

    // 绘制文字旁圆点
    ctx.beginPath();
    console.log(text1_width)
    ctx.arc((canvas.width - text1_width) / 2 - 7, y - 3.5 - 25, 7, 0, Math.PI * 2);
    ctx.fillStyle = color1;
    ctx.fill();
    ctx.save();
    ctx.beginPath();
    console.log(text2_width)
    ctx.arc((canvas.width - text2_width) / 2 - 7, y - 3.5 - 5, 7, 0, Math.PI * 2);
    ctx.fillStyle = color2;
    ctx.fill();
  }
</script>

</html>
上一篇下一篇

猜你喜欢

热点阅读