用canvas来画一个饼状图

首先,效果图呈上—
在这里插入图片描述
在js文件中

    let Piecharts = function (selector, options) {
        let canvas = "string" === typeof selector ? document.querySelector(selector) : null;
        if (canvas === null) return false;
        let defaultOptions = {
            radius: 200,
            legendParms: {
                font: "24px Arial",
                x: 30,
                y: 30,
                margin: 50,
                width: 40,
                height: 24
            }
        }
        this.ctx = canvas.getContext("2d");
        this.width = canvas.getAttribute("width") || 300;
        this.height = canvas.getAttribute("height") || 300;
        this.options = Object.assign(defaultOptions, options); //Object.assign(source,target)
        
    }
    

    Piecharts.prototype.load = function (data) {
        // console.log('this.ctx'+this.ctx);
        data.forEach(item => this.count ? this.count += item.value : this.count = item.value);
        this.data = data;
        return this;
    };

    Piecharts.prototype.render = function () {
        let _generateLegand = (item, index) => {
            this.ctx.fillRect( // fillRect(x,y,width,height)方法绘制“已填色”的矩形。默认的填充颜色是黑色。 x,y 是矩形左上角的坐标
                this.options.legendParms.x,
                this.options.legendParms.y + index * this.options.legendParms.margin,
                this.options.legendParms.width,
                this.options.legendParms.height
            );
            this.ctx.font = this.options.legendParms.font;
            this.ctx.fillText( //fillText(text,x,y,maxWidth)
                item.title,
                this.options.legendParms.y + this.options.legendParms.margin,
                (index + 1) * this.options.legendParms.margin
            );
        };
        let temparc = 0;
        this.data.forEach((item, index) => {
            item.color = `#${('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6)}`;
            this.ctx.beginPath(); //开始一条路径
            this.ctx.moveTo(this.width / 2, this.height / 2);
            let startarc = temparc,
                endarc = startarc + (item.value / this.count) * Math.PI * 2; //根据data中的value值来确定圆弧的大小
            this.ctx.arc( //创建弧/曲线(用于创建圆形或部分圆)context.arc(x,y,r,sAngle,eAngle,counterclockwise);counterclockwise	可选。规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针。
                this.width / 2,
                this.height / 2,
                this.options.radius,
                startarc,
                endarc,
                false
            );
            this.ctx.closePath();  //结束一条路径
            this.ctx.fillStyle = item.color;
            this.ctx.fill();
            temparc = endarc;
            if (this.options.legend) {
                _generateLegand(item, index)
            }
        });
        return this;
    }

在html文件中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>pie-charts</title>
    <script src="./demo.js"></script>

</head>
<body>
    <pre>
        canvas 常用api
        var canvas = document.getElementById("canvas");  //获取canvas 对象
        var ctx = canvas.getContext("2d");  //获得上下文对象
        ctx.fillStyle = "rgb(200,0,0)";  //设置或返回用于填充绘画的颜色、渐变或模式
        ctx.fillRect (10, 10, 55, 50); //绘制“被填充”的矩形
        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
        //画了个矩形
    </pre>

    <canvas class="pie-charts" width="850" height="500"></canvas>
    <script>
    const data = [{
            title: 'piecharts-1',
            value: 1024
        },
        {
            title: 'piecharts-2',
            value: 2012
        },
        {
            title: 'piecharts-3',
            value: 588
        },
        {
            title: 'piecharts-4',
            value: 1000
        }
    ];
        var pie = new Piecharts(".pie-charts", {
            legend: true
        });
        pie.load(data).render();</script>
</body>
</html>
原文链接:加载失败,请重新获取