小程序通过canvas快速绘制饼状图

365 阅读1分钟

小程序通过canvas快速绘制饼状图

        <canvas  id="myCanvas" type="2d"/>
        getCanvas() {
            let colors = ['#f58f98', '#78a355', '#fab27b', '#4e72b8', '#ffd400'];
            let query = wx.createSelectorQuery().in(this); // 封装组件情况下需要传入this
            // 在 WXML 中填入的 id
            query.select('#myCanvas').node(({node: canvas}) => {
                const ctx = canvas.getContext('2d')
                ctx.clearRect(0, 0, canvas.width, canvas.height)
                const dpr = wx.getSystemInfoSync().pixelRatio
                //宽高乘像素比--防止图形模糊
                canvas.width = canvas.width * dpr
                canvas.height = canvas.height * dpr
                //再缩放
                ctx.scale(dpr, dpr)

                let start = 0
                let end = 0
                let arr = [25,10, 20, 0, 25]
                let sum = 80
                for (let i = 0; i < arr.length; i++) {
                    end = end + Math.PI * 2 * arr[i] / sum
                    ctx.beginPath()
                    // 起点位置
                    ctx.moveTo(50, 50)
                    // 绘制圆的对应部分图形
                    // arc参数:(中心点x坐标,中心点y坐标,半径大小,起始角度,结束角度,角度是否逆时针计算)
                    ctx.arc(50, 50, 50, start, end, false)
                    // 设置填充颜色
                    ctx.fillStyle = colors[i]
                    // 圆弧回到中心点位置
                    ctx.lineTo(50, 50)
                    // 填充颜色
                    ctx.fill()
                    start = end
                }

                //绘制中空白色圆
                ctx.beginPath();
                ctx.fillStyle = 'white';
                ctx.arc(50,50,26,0,2*Math.PI,false);
                ctx.fill();

            }).exec()
        }