美文网首页程序员
用Canvas画个圆盘

用Canvas画个圆盘

作者: 单调先生 | 来源:发表于2018-07-12 09:43 被阅读208次

    需求的来源通常是工作,这次要完成功能核心是一个向量图,嗯...其实就是一个定制化的仪表盘,换做平时一个上午就能搞定,只要数据给到顺手测试了就交货,但这次却有些不一样,这次要完成的,是一个微信小程序。嗯,小程序有什么不同呢?答案是小程序没有好用的仪表盘插件库,网上搜了一下感觉都不太符合需求,没法子只能自己手动搞一个,但没关系,我甚至还有一点点激动,因为可以乘机玩一下Canvas

    需求及目标

    这里绘制一个半径RADIUS = 300的外圆,为了实验我将用常规的Web代码编写。最终完成品如下。

    向量图

    解决的问题

    目标清晰了,就大概知道怎么走了。从图中可以看出整个图就是一个表盘+表针的表现形式,细节在于表盘和表针的样式,接下来我们一一分析

    1. 表盘的制作

    可以看到表盘的中心是空的,圆边有刻度线,且还有相应的刻度标识。那么问题来了:

    • 如何让表盘的中心看起来像空?这个问题很简单,画两个圆即可。首先画外圆,选择填充样式,具体代码如下
    ctx.translate(RADIUS, RADIUS); //坐标原点
    ctx.beginPath();
    ctx.arc(0, 0, RADIUS - 2, 0, 2 * PI); //绘制圆
    ctx.strokeStyle = '#3F51B5';  //边框样式
    ctx.fillStyle = '#EEEEEE';  //填充样式
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
    

    其次在外圆的基础上绘制一个空白的内圆,效果便出来了

    ctx.beginPath();
    ctx.arc(0, 0, RADIUS * 2 / 3, 0, 2 * PI); //绘制圆
    ctx.strokeStyle = '#3F51B5';
    ctx.fillStyle = '#fff';
    ctx.fill()
    ctx.stroke();
    ctx.closePath();
    
    基础空心圆
    • 如何画刻度线?
      一个圆有360°,也就是说要在圆弧上标上360个刻度(废话)。这里需要的做法是每画一个刻度则旋转一度,但这里要注意,rotate(deg)需要传入的是弧度,所以需要做一个转化。但首先,弧度的概念了解一下: 来自维基百科的弧度定义
      可以从上面推出,假设我们要旋转一度,则需要做如下操作ctx.rotate((PI / 180 * i) - (PI / 2));。另外需要注意的一个点,每次对画布改变状态之前都要调用save()方法,保存上一帧的画面,待操作完毕后调用restore()恢复,刻度代码如下
        //表盘刻度
        for (let i = -180; i < 180; i++) {
            ctx.save();
            ctx.rotate((PI / 180 * i) - (PI / 2)); //旋转坐标轴
            if (i % 20 === 0) {
                ctx.fillText(-i, RADIUS - 40, 0);    //每20个刻度打上刻度标签
            }
            ctx.beginPath();
            ctx.moveTo(RADIUS - 17, 0);
            ctx.lineTo(RADIUS - 7, 0);
            ctx.lineWidth = (i % 20) !== 0 ? 1 : 2; //每20个指针加粗一次
            ctx.strokeStyle = (i % 20) !== 0 ? '#BDBDBD' : '#2196F3';
            ctx.stroke();
            ctx.closePath();
            ctx.restore();
        }
    

    最终效果如下:


    表盘

    2. 指针的制作

    用canvas画一根线是不难的,一个路径API调用就可以了,但是,要怎么画一个有箭头的线呢?这个想法其实不难,就是通过在线末端画多两根线就好了,难点在于怎么确定箭头两个线的坐标及角度的问题,这里就需要用到三角函数来定位了。具体可参考这篇教程

    3. 跟随数据的转动

    ……这个在有需要的时候调用该函数就可以了,比如在我自己的项目中,我需要根据数据的变动来调整,则在请求数据后调用该方法即可

    完整代码

    const canvas = document.getElementById('chart');
    const ctx = canvas.getContext('2d');
    const PI = Math.PI;
    const RADIUS = 300; //半径
    
    /**
     * 渲染表盘
     * @param {CanvasRenderingContext2D} ctx
     */
    function renderDial(ctx) {
        ctx.clearRect(0, 0, RADIUS * 2, RADIUS * 2);
        ctx.save();
        //外圆定中心
        ctx.translate(RADIUS, RADIUS); //坐标原点
        ctx.beginPath();
        ctx.arc(0, 0, RADIUS - 2, 0, 2 * PI); //绘制圆
        ctx.strokeStyle = '#3F51B5';
        ctx.fillStyle = '#EEEEEE'
        ctx.fill();
        ctx.stroke();
        ctx.closePath();
    
        //内圆
        ctx.beginPath();
        ctx.arc(0, 0, RADIUS * 2 / 3, 0, 2 * PI); //绘制圆
        ctx.strokeStyle = '#EEEEEE';
        ctx.fillStyle = '#fff';
        ctx.fill()
        ctx.stroke();
        ctx.closePath();
    
        //中心点
        ctx.beginPath();
        ctx.arc(0, 0, 10, 0, 2 * PI);
        ctx.fillStyle = '#000';
        ctx.fill()
        ctx.closePath();
    
        //表盘刻度
        for (let i = -180; i < 180; i++) {
            ctx.save();
            ctx.rotate((PI / 180 * i) - (PI / 2)); //旋转坐标轴
            if (i % 20 === 0) {
                ctx.fillText(-i, RADIUS - 40, 0);
            }
            ctx.beginPath();
            ctx.moveTo(RADIUS - 17, 0);
            ctx.lineTo(RADIUS - 7, 0);
            ctx.lineWidth = (i % 20) !== 0 ? 1 : 2; //每20个指针加粗一次
            ctx.strokeStyle = (i % 20) !== 0 ? '#BDBDBD' : '#2196F3';
            ctx.stroke();
            ctx.closePath();
            ctx.restore();
        }
        ctx.restore();
    }
    
    /**
     * 渲染表针
     * @param {CanvasRenderingContext2D} ctx
     */
    function renderHands(ctx, angleA, angleB, angleC) {
        //角度转化成弧度
        let angle = PI / 180 * angleA;
        let angle1 = PI / 180 * angleB;
        let angle2 = PI / 180 * angleC;
        // drawHand(angle, 250, 5, '#2196F3', ctx)
        drawArrow(ctx, angle, RADIUS * 5 / 6, 5, 15, 20, '#2196F3', 'A')
        drawArrow(ctx, -angle1, RADIUS * 5 / 6, 5, 15, 20, '#2196F3', 'B')
        drawArrow(ctx, -angle2, RADIUS * 5 / 6, 5, 15, 20, '#2196F3', 'C')
    
    }
    
    /**
     * 渲染表针
     * @param {CanvasRenderingContext2D} ctx
     * @param {Number} angle 弧度
     * @param {Number} len 线长
     * @param {Number} width 线宽度
     * @param {Number} theta 三角斜边 —— 直线夹角
     * @param {Number} headlen 三角斜边长度
     * @param {String} color 线条颜色
     */
    function drawArrow(ctx, angle, len, width, theta, headlen, color, text) {
        let arrowAngle = Math.atan2(0, len) * 180 / Math.PI,
            angle1 = (arrowAngle + theta) * PI / 180,
            angle2 = (arrowAngle - theta) * PI / 180,
            topX = headlen * Math.cos(angle1),
            topY = headlen * Math.sin(angle1),
            botX = headlen * Math.cos(angle2),
            botY = headlen * Math.sin(angle2);
    
        ctx.save();
        ctx.translate(RADIUS, RADIUS);
        ctx.rotate(-Math.PI / 2 + angle);
        ctx.beginPath();
    
        let arrowX = -4 - topX,
            arrowY = 0 - topY;
    
        // ctx.moveTo(arrowX, arrowY);
        /* 绘制直线 */
        ctx.moveTo(-4, 0);
        ctx.lineTo(len, 0);
    
        arrowX = len - topX;
        arrowY = topY;
        ctx.moveTo(arrowX, arrowY);
        ctx.lineTo(len, 0);
    
        arrowX = len - botX;
        arrowY = botY;
        ctx.lineTo(arrowX, arrowY);
    
        ctx.strokeStyle = color;
        ctx.lineWidth = width;
    
        ctx.stroke();
        ctx.closePath();
        ctx.restore()
    
        ctx.save();
        ctx.translate(RADIUS, RADIUS)
        ctx.rotate(-Math.PI / 2 + angle);
    
        ctx.translate(len - 50, 0);
        ctx.rotate(90 * Math.PI / 180);
        ctx.font = '16px bold sans-serif'
        ctx.fillText(text, -20, -10);
    
        ctx.restore();
    }
    
    renderDial(ctx)
    renderHands(ctx, 0, -120, 120);
    

    相关文章

      网友评论

        本文标题:用Canvas画个圆盘

        本文链接:https://www.haomeiwen.com/subject/iedoeftx.html