canvas画圆环(一)之渐变色,纯色

通过canvas画可自定义纯色或渐变色的圆环,可当进度条使用,本文章做了简单的封装可直接使用,也可自定义更改

html结构

需要设置外层的item-canvas的宽高,内层canvas会设置成和外层一样。

javascript

定义函数

function process() {
        var ring = arguments[0]; //获取传入的第一个参数
        var canvas = document.getElementById(ring.canvasId);
        var context = canvas.getContext('2d');
        var center = [(ring.canvasW) / 2, (ring.canvasH) / 2];
        var borderWidth = ring.bdWidth;
        var r = ring.canvasW / 2 - borderWidth / 2; //因内层canvas的宽度和外层相等,所以需要减去圆环的宽度
        context.clearRect(0, 0, ring.canvasW, ring.canvasH); //清除canvas
        //开始画一个灰色的圆
        context.save();
        context.beginPath();
        context.lineWidth = borderWidth;
        context.strokeStyle = ring.bgcolor;
        context.arc(center[0], center[1], r, 0, 2 * Math.PI, false);
        context.stroke();
        context.restore();
        //设置渐变色,做了简单的判断传入的是渐变色或者纯色
        if (ring.color) {
                var gradient = context.createLinearGradient(ring.x1, ring.y1, ring.x2, ring.y2);
                ring.color.forEach(element => {
                        gradient.addColorStop(element.step, element.color);
                });
                context.strokeStyle = gradient;
        }
        if (ring.strokeColor) {
                context.strokeStyle = ring.strokeColor;
        }
        /*此处是添加圆环内部的文字*/
        context.save();
        context.beginPath();
        context.font = "20px Georgia";
        context.textAlign="center"; //基于基线水平居中,垂直目前没好的方法,有请告知
        context.fillStyle = gradient;
        context.fillText(ring.percent+"%", center[0] , center[1] ); 
        context.restore();
        //外层圆环
        context.save();
        context.beginPath();
        context.lineWidth = borderWidth;
        context.arc(center[0], center[1], r, 0, 2 * ring.percent / 100 * Math.PI, false);
        context.lineCap = "round";
        context.stroke();
        context.restore();
}

简单封装

//测试用渐变色
var arr = [{
        step: '0',
        color: '#43e8ff'
}, {
        step: '0.4',
        color: '#8024db'
}, {
        step: '0.6',
        color: '#a044ff'
}, {
        step: '0.9',
        color: '#5205ce'
}, {
        step: '1',
        color: '#25c1fb'
}];
var divItem = document.querySelector(".item-canvas");
var canvasW = divItem.offsetWidth; //获取外层div宽高,然后赋值给canvas
var canvasH = divItem.offsetWidth;
process({
        canvasId: "procanvas1",  //canvas的Id
        canvasW: canvasW,        //canvas的width
        canvasH: canvasH,        //canvas的height
        bdWidth: 10,          //圆环的宽
        color: arr,              //渐变需要设置渐变的颜色及占用的百分比需要写小数
        bgcolor: "gray",         //圆环的背景颜色
        //strokeColor:"red",       //纯色,没渐变写
        x1: canvasW / 2,                   //渐变的起始位置和结束位置x1,y1,x2,y2
        y1: canvasH,
        x2: canvasW / 2,
        y2: 0,
        percent: 100,             //转过的百分比

})

效果如下图:
canvas画圆环(一)之渐变色,纯色_第1张图片

你可能感兴趣的:(代码段)