canvas写圆环

export function initCanvas(obj) {
    this.x0 = obj.x0 // 圆心坐标
    this.y0 = obj.y0 // 圆心坐标

    this.r1 = obj.r1 // 外圆半径
    this.endAng = obj.endAng // 终点角度
    this.gradient = obj.color //颜色
    this.degActive = 0

    this.canvas = document.getElementById(obj.el);
    var width = this.canvas.width
    var height = this.canvas.height
    this.canvas.style.height = height + "px";
    this.canvas.style.width = width + "px";
    this.canvas.height = height * 4;
    this.canvas.width = width * 4;

    this.ctx = this.canvas.getContext("2d");
    this.ctx.scale(4, 4)

    this.timer = setInterval(() => {
        if (this.degActive > this.endAng / 100 * 360) { //停止定时器
            clearInterval(this.timer);
        } else {
            this.ctx.clearRect(0, 0, width, height);//清除画布
            let txt = (parseInt(this.degActive * 100 / 360) + "%");//获取百分比
            this.ctx.font = 20 + "px SimHei";
            let w = this.ctx.measureText(txt).width;//获取文本宽度
            let h = 12 ;
            this.ctx.fillStyle = "#fff";
            this.ctx.fillText(txt,this.x0-w/2, this.y0+h/2);



            this.degActive++;
            if (this.endAng <= 50) {
                this.gradient = this.ctx.createLinearGradient(0, 0, 0, 120);
                this.gradient.addColorStop(0, obj.color[0]);
                this.gradient.addColorStop(1, obj.color[1]);

            } else if (this.endAng >= 50 && this.endAng < 100) {
                this.gradient = this.ctx.createLinearGradient(-120, 0, 0, 120);
                this.gradient.addColorStop(0, obj.color[0]);
                this.gradient.addColorStop(1, obj.color[1]);

            } else if (this.endAng >= 100) {
                this.gradient = this.ctx.createLinearGradient(88, 168, 88, 0);
                this.gradient.addColorStop(0, obj.color[0]);
                this.gradient.addColorStop(1, obj.color[1]);

            }

            drawColorArc(obj, this.degActive, this.gradient, this.ctx)
        }

    },this.timer)
}

function drawColorArc(obj, degActive, gradient, ctx) {
    ctx.beginPath(); //开始绘制底圆
    ctx.lineWidth = obj.lineWidth;
    ctx.arc(obj.x0, obj.y0, obj.r1, 0, Math.PI * 2, false);
    ctx.strokeStyle = "#fff";
    ctx.stroke();
    ctx.beginPath(); //开始绘制动态圆

    ctx.arc(obj.x0, obj.y0, obj.r1, Math.PI / 2, (Math.PI / 180) * degActive + Math.PI / 2, false);

    ctx.lineWidth = obj.lineWidth;
    ctx.strokeStyle = gradient;
    ctx.lineCap = "round"
    ctx.stroke();
}
 new initCanvas({ el: "cavans_man", color: ["#73fbe9", "#fff"], x0: 30, y0: 30, endAng: 50, r1: 25, lineWidth: 10 });

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值