How to implement canvas ring countdown component

不言
Release: 2018-06-14 16:08:34
Original
1810 people have browsed it

This article mainly introduces the sample code of the canvas ring countdown component. The content is quite good. I will share it with you now and give it as a reference.

This article introduces the sample code of the canvas ring countdown component and shares it with everyone. The details are as follows:

The effect is as shown in Figure 1:

Canvas ring countdown component

Canvas ring countdown is a countdown based on Canvas. It is recommended to use it on the mobile terminal

Canvas ring countdown download address

1. How to use

1. html code

The ID attribute can be named as you like

<canvas id="canvas"></canvas>
Copy after login
Copy after login

2. Introduce process.js file

Page reference

<script src="js/process.js"></script>
Copy after login

3. Initialization parameters

Example Just change

<script>
    window.onload = function () {
        let ctd = new Countdown();
        ctd.init();
    };

</script>
Copy after login

2. Description of settings parameters

The following parameters are not required , can be configured according to specific needs

window.onload = function () {
        let ctd = new Countdown();
        ctd.init({
            id: "canvas",         // ID,canvas一定要有ID属性
            size: 130,            // 绘制圆形的最大尺寸,宽=高
            borderWidth: 4,       // 边框宽度
            borderColor:"#fff",   // 边框颜色
            outerColor:"#fff",    // 最外层底圆颜色
            scheduleColor:"#fff", // 进度条动画颜色
            fontColor: "#fff",    // 字体颜色
            ringColor: "#ffc720", // 进度条环形颜色
            innerColor: "#4e84e5",// 最内圆底色
            fontSize: 50,
            time: 5
        });
    };
Copy after login

3. Sample code

html




    
    Title
    


<script src="js/process.js"></script> <script> window.onload = function () { let ctd = new Countdown(); ctd.init(); }; </script>
Copy after login

js

/**
 * Created by 谭瞎 on 2018/3/15.
 */

function Countdown() {
    // 设置默认参数
    this.settings = {
        id: "canvas",         // ID,canvas一定要有ID属性
        size: 130,            // 绘制圆形的最大尺寸,宽=高
        borderWidth: 4,       // 边框宽度
        borderColor:"#fff",   // 边框颜色
        outerColor:"#fff",    // 最外层底圆颜色
        scheduleColor:"#fff", // 进度条动画颜色
        fontColor: "#fff",    // 字体颜色
        ringColor: "#ffc720", // 进度条环形颜色
        innerColor: "#4e84e5",// 最内圆底色
        fontSize: 50,
        time: 5
    }
}

Countdown.prototype.init = function (opt) {
    this.obj = document.getElementById(this.settings.id);
    this.obj.width = this.settings.size;
    this.obj.height = this.settings.size;
    this.ctx = this.obj.getContext("2d");
    extend(this.settings, opt);
    this.countdown();
};

// 绘制底色
Countdown.prototype.drawBackground = function () {
    this.drawCircle(0, 360, 0, this.settings.outerColor);
};
// 绘制进度条动画背景
Countdown.prototype.drawProcess = function () {
    this.drawCircle(0, 360, 4, this.settings.ringColor);
};

// 绘制倒计时
Countdown.prototype.drawInner = function () {
    this.drawCircle(0, 360, 23, this.settings.innerColor);
    this.strokeBorder(this.settings.borderWidth);
};

// 绘制进度条动画
Countdown.prototype.drawAnimate = function () {
    // 旋转的角度
    let deg = Math.PI / 180;
    let v = schedule * 360,
        startAng = -90,
        endAng = -90 + v;

    this.ctx.beginPath();
    this.ctx.moveTo(this.settings.size / 2, this.settings.size / 2);
    this.ctx.arc(this.settings.size / 2, this.settings.size / 2, this.settings.size / 2 -3, startAng * deg, endAng * deg, false);
    this.ctx.fillStyle = this.settings.scheduleColor;
    this.ctx.fill();
    this.ctx.closePath();

};
// 绘制边框
Countdown.prototype.strokeBorder = function (borderWidth) {
    this.ctx.lineWidth = borderWidth;
    this.ctx.strokeStyle = this.settings.borderColor;
    this.ctx.stroke();
};
// 绘制文字
Countdown.prototype.strokeText = function (text) {
    this.ctx.textAlign = "center";
    this.ctx.textBaseline = "middle";
    this.ctx.font = this.settings.fontSize+"px"+ " microsoft yahei";
    this.ctx.fillStyle = this.settings.fontColor;
    this.ctx.fillText(text, this.settings.size / 2, this.settings.size / 2);
};
// 绘制圆
Countdown.prototype.drawCircle = function (startAng, endAng, border, fillColor) {
    let deg = Math.PI / 180;
    this.ctx.beginPath();
    this.ctx.arc(this.settings.size / 2, this.settings.size / 2, this.settings.size / 2 -border, startAng * deg, endAng * deg, false);
    this.ctx.fillStyle = fillColor;
    this.ctx.fill();
    this.ctx.closePath();
};
// 进度条动画
Countdown.prototype.countdown = function () {
    let oldTime = +new Date();
    timer = setInterval(() => {
        let allMs = this.settings.time * 1000,// 如30*1000=30 000ms
            currentTime = +new Date();
        // 步长=(当前的时间-过去的时间)/总秒数
        schedule = (currentTime - oldTime) / allMs;
        this.schedule = schedule;

        this.drawAll(schedule);
        if (currentTime - oldTime >= allMs) {
            // 重绘
            this.drawBackground();
            this.drawProcess();
            this.drawAnimate();
            this.drawInner();
            this.strokeText(0);
            clearInterval(timer);
        }
    }, 100);
};

// 绘制所有
Countdown.prototype.drawAll = function (schedule) {
    schedule = schedule >= 1 ? 1 : schedule;
    let text = parseInt(this.settings.time * (1 - schedule)) + 1;
    // 清除画布
    this.ctx.clearRect(0, 0, this.settings.size, this.settings.size);
    this.drawBackground();
    this.drawProcess();
    this.drawAnimate();
    this.drawInner();
    this.strokeText(text);
};

// 对象拷贝
function extend(obj1,obj2){
    for(let attr in obj2){
        obj1[attr] = obj2[attr];
    }
}
Copy after login

##4. Additional - canvas preparation Work

canvas is actually not that mysterious. It is nothing more than an H5 tag, just like other HTML tags:

<canvas id="canvas"></canvas>
Copy after login
Copy after login

Note that it is best to set the width and height of the canvas at the beginning (if the width and height are not set, the browser will default to setting the canvas size to 300 pixels wide and 100 pixels high), and it cannot be set using css (will be stretched), it is recommended to write directly inside the canvas tag:

<canvas id="canvas" width="130" height="130"></canvas>
Copy after login

canvas itself does not have any drawing capabilities, all drawing work is done through js to achieve. Usually we use getElementById in js to get the canvas to be operated (which means we have to set an id for the canvas):

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
Copy after login

1. After preparing the brush, You can start drawing. Rings are actually concentric circles with different radii. The center coordinates are (size/2, size/2). First, draw the largest bottom circle with a white background, and the radius is size/2.

let deg = Math.PI / 180;
// beginPath()可以做到隔离路径绘制效果的作用,防止之前的效果被污染。
ctx.beginPath();

// tcx.arc(圆心X,圆心Y,半径,起始角度,结束角度,顺逆时针);
ctx.arc(size / 2, size / 2, size / 2, 0* deg, 360 * deg, false);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.closePath();
Copy after login

2. Start drawing a second yellow circle with a center center also (size/2, size/2 ), but the radius is 4px smaller than the white bottom circle, so the radius of the yellow bottom circle is (size/2-4)

##
let deg = Math.PI / 180;
// beginPath()可以做到隔离路径绘制效果的作用,防止之前的效果被污染。
ctx.beginPath();

// tcx.arc(圆心X,圆心Y,半径,起始角度,结束角度,顺逆时针);
ctx.arc(size / 2, size / 2, size / 2-4, 0* deg, 360 * deg, false);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.closePath();
Copy after login

3. Start drawing a blue inner circle, the center of the circle is (size/2, size/2), the radius is (size-23), and then add a 4px white border to it.

let deg = Math.PI / 180;
// beginPath()可以做到隔离路径绘制效果的作用,防止之前的效果被污染。
ctx.beginPath();

// tcx.arc(圆心X,圆心Y,半径,起始角度,结束角度,顺逆时针);
ctx.arc(size / 2, size / 2, size / 2-23, 0* deg, 360 * deg, false);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.closePath();

// 白色边框
ctx.lineWidth = 4;
ctx.strokeStyle = #fff;
ctx.stroke();
Copy after login

4. Draw text and center it vertically

ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#fff";
// ctx.fillText(文字,相对画布的X坐标,相对画布的Y坐标)
ctx.fillText(30, size / 2, size / 2);
Copy after login

5. How to make animation? In fact, it is also a process of drawing a white circle, a process of slowly covering the yellow progress bar. Then draw the white circle first. At this time, the blue circle will be covered by the white animated circle. At this time, the last blue circle will be drawn. alright.

let deg = Math.PI / 180;
ctx.beginPath();
// tcx.arc(圆心X,圆心Y,半径,起始角度,结束角度,顺逆时针);
ctx.arc(size / 2, size / 2, size / 2-4, 0* deg, 360 * deg, false);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.closePath();
Copy after login

6. The relatively simple painting process is completed. Next, we need to associate the animation with the numbers and use the current The latest time - the most starting time, and then dividing the total time can get a key percentage. This percentage determines the change of the number and the angle at which the white animated circle is drawn.

Countdown.prototype.countdown = function () {
    let oldTime = +new Date();// 过去的时间:1522136419291
    timer = setInterval(() => {
        let currentTime = +new Date();// 现在的时间:1522136419393
        let allMs = this.settings.time * 1000;// 总时间豪秒数:如30*1000=30 000ms
        schedule = (currentTime - oldTime) / allMs;// 绘制百分比:(1522136419393-1522136419291)/30000=0.0204
        this.schedule = schedule;
        this.drawAll(schedule);
        if (currentTime - oldTime >= allMs) {
            // 重绘
            this.drawBackground();
            this.drawProcess();
            this.drawAnimate();
            this.drawInner();
            this.strokeText(0);
            clearInterval(timer);
        }
    }, 10);
};

// 绘制所有
Countdown.prototype.drawAll = function (schedule) {
    schedule = schedule >= 1 ? 1 : schedule;
    let text = parseInt(this.settings.time * (1 - schedule)) + 1;
    // 清除画布
    this.ctx.clearRect(0, 0, this.settings.size, this.settings.size);
    this.drawBackground();
    this.drawProcess();
    this.drawAnimate();
    this.drawInner();
    this.strokeText(text);
};

// 绘制进度条动画
Countdown.prototype.drawAnimate = function () {
    // 旋转的角度
    let deg = Math.PI / 180;
    let v = schedule * 360,
        startAng = -90,// 开始角度
        endAng = -90 + v;// 结束角度

    this.ctx.beginPath();
    this.ctx.moveTo(this.settings.size / 2, this.settings.size / 2);
    this.ctx.arc(this.settings.size / 2, this.settings.size / 2, this.settings.size / 2 - 3, startAng * deg, endAng * deg, false);
    this.ctx.fillStyle = this.settings.scheduleColor;
    this.ctx.fill();
    this.ctx.closePath();
};
Copy after login

Process-oriented version

/**
    * 进度条动画
    */
    countdown: function () {
        this.getSystemInfo().then(v => {
            // 自适应
            let width = v.windowWidth,
                size = width >= 414 ? 66 : 400 / 414 * 66;
            size = parseInt(size);
            size = size % 2 ? size + 1 : size;

            let maxtime =30,
                sTime = +new Date,

                temp = setInterval(() => {
                    let time = maxtime * 1000,
                        currentTime = +new Date,
                        schedule = (currentTime - sTime) / time;

                    this.drew(schedule, maxtime, size);

                    if (currentTime - sTime >= time) {
                        // 绘制文字
                        this.setData({
                            schedule: 0
                        });
                        clearInterval(temp);
                    };
                }, 100);

        });
    },

    /**
     * 绘制
     */
    drew: function (schedule, val, size) {
        size = size || 66;
        const _ts = this;
        schedule = schedule >= 1 ? 1 : schedule;

        let text = parseInt(val - val * schedule),
            r = size / 2,
            deg = Math.PI / 180;

        _ts.setData({
            width: size,
            height: size,
            schedule: text + 1
        });

        // 清除画布
        ctx.clearRect(0, 0, size, size);

        // 绘制白色底
        ctx.beginPath();
        ctx.arc(r, r, r, 0 * deg, 360 * deg);
        ctx.fillStyle = &#39;rgba(255,255,255,1)&#39;;
        ctx.closePath();
        ctx.fill();

        // 绘制橙色
        ctx.beginPath();
        ctx.arc(r, r, r - 2, 0 * deg, 360 * deg);
        ctx.fillStyle = &#39;rgba(248,200,80,1)&#39;;
        ctx.closePath();
        ctx.fill();

        // 绘制白色进度条
        let v = schedule * 360;

        ctx.beginPath();
        ctx.moveTo(r, r);
        ctx.arc(r, r, r, -90 * deg, (-90 + v) * deg);

        ctx.fillStyle = &#39;rgba(255,255,255,1)&#39;;
        ctx.closePath();
        ctx.fill();

        // 中心蓝色底
        ctx.beginPath();
        ctx.arc(r, r, r - 12, 0 * deg, 360 * deg);
        ctx.fillStyle = &#39;rgba(90,140,220,1)&#39;;
        ctx.closePath();
        ctx.fill();

        // 绘制文字
        ctx.strokeText();
        
        // 统一画
        ctx.draw();
            
    },
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to use Canvas to operate pixels


##About the properties of canvas lines


How to use canvas to implement image mosaic


The above is the detailed content of How to implement canvas ring countdown component. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template