使用canvas写一个饼状图

本文将介绍如何利用HTML5的canvas元素结合JavaScript,详细步骤地实现一个动态的饼状图绘制过程,包括设置画布、计算角度、绘制扇形等关键步骤。
摘要由CSDN通过智能技术生成

使用canvas写一个饼状图
在这里插入图片描述

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id='canvas' width='800' height='400' style="border: 1px solid red;"></canvas>

    <script>
        let data = [
            { title: "服饰1", money: 400 },
            { title: "服饰2", money: 300 },
            { title: "服饰3", money: 400 },
            { title: "服饰4", money: 200 },
            { title: "服饰5", money: 500 },
            { title: "服饰6", money: 180 },
            { title: "服饰7", money: 500 }]

        /** @type {HTMLCanvasElement} */
        let canvas = document.querySelector("#canvas");
        let ctx = canvas.getContext("2d");
        let r = 100;

        let money = function (obj, sum) {
            for (let i = 0; i < obj.length; i++) {
                sum += data[i].money
                
            }
            return sum;
        }
        let totalmoney = money(data, 0);

        let nowsum = 0;
        let start = 0;
        let end = 0;
        let R = 100;
        let i=0;
        data.forEach(function (item) {
            ctx.beginPath()
            nowsum += item.money;
            end = (nowsum / totalmoney) 
            ctx.moveTo(150, 150);
            ctx.arc(150, 150, R, start*Math.PI*2, end*Math.PI*2)
            start = end;
            //产生随机颜色
            ctx.fillStyle = '#' + Math.floor(Math.random() * 0xffffff).toString(16);
            ctx.rect(350,5+(35*i),30,30);
            ctx.font="14px 黑体"
            ctx.fillText(item.title,400,25+(35*i))
            ctx.strokeStyle = "gray"
            ctx.fill();
            ctx.stroke();
            i++;
        })
    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值