How to implement the canvas ring Countdown component

Source: Internet
Author: User
Tags border color
This article mainly introduces the canvas ring Countdown Component Sample code, the content is very good, now share to everyone, but also for everyone to make a reference.

This article describes the sample code for the canvas ring countdown component, which is shared with you, as follows:

The effect is as follows:

Canvas Ring Countdown Component

The canvas ring countdown is a canvas-based countdown that is recommended for use on the mobile side

Canvas Ring Countdown Download Address

First, how to use

1. HTML code

ID attribute can be arbitrarily named

<canvas id= "Canvas" ></canvas>

2. Introduction of Process.js Files

Page references

<script src= "Js/process.js" ></script>

3. Initializing parameters

Instantiation can

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

Second, settings parameter description

The following parameters are not required and can be configured according to your specific requirements

Window.onload = function () {let        ctd = new Countdown ();        Ctd.init ({            ID: "Canvas",         //Id,canvas must have the id attribute            size:130,            //Draw the maximum size of the circle, width = high            borderwidth:4,       //Border width            bordercolor: "#fff",   //Border color            outercolor: "#fff",    //Outermost bottom circle color            schedulecolor: "# FFF ",//progress bar animation color            fontcolor:" #fff ",    //Font color            ringcolor:" #ffc720 ",//progress bar ring color            innercolor:" #4e84e5 " ,//The most inner circle background            fontsize:50,            time:5        }    );

Three, sample code

Html

<! DOCTYPE html>

Js

/** * Created by Tan Blind on 2018/3/15. */function countdown () {//set default parameter This.settings = {id: "canvas",//Id,canvas Be sure to have an id attribute of size: 130,//Draw the maximum size of the circle, width = high borderwidth:4,//Border width bordercolor: "#fff",//Border color Outercol Or: "#fff",//Outermost bottom circle color schedulecolor: "#fff",//progress bar animation color fontcolor: "#fff",//Font Color ringcolor: "# ffc720 ",//progress bar ring Color Innercolor:" #4e84e5 ",//the most inner circle background fontsize:50, Time:5}}countdown.prototype.ini    t = 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 ();};/ /Draw the background Countdown.prototype.drawBackground = function () {this.drawcircle (0, 0, this.settings.outerColor);};/ /Draw progress bar animated background Countdown.prototype.drawProcess = function () {this.drawcircle (0, 4, This.settings.ringCOlor);};/    /Draw Countdown Countdown.prototype.drawInner = function () {this.drawcircle (0, This.settings.innerColor); This.strokeborder (this.settings.borderWidth);};/    /Draw progress bar Animation Countdown.prototype.drawAnimate = function () {//rotation angle let deg = math.pi/180;    Let V = schedule *, 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, Fals    e);    This.ctx.fillStyle = This.settings.scheduleColor;    This.ctx.fill (); This.ctx.closePath ();};/    /Draw Border Countdown.prototype.strokeBorder = function (borderWidth) {this.ctx.lineWidth = BorderWidth;    This.ctx.strokeStyle = This.settings.borderColor; This.ctx.stroke ();};/    /Draw Text 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);};/    /Draw Circle 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 ();};/    /progress bar Animation Countdown.prototype.countdown = function () {Let oldtime = +new Date (); Timer = SetInterval (() = {Let Allms = This.settings.time * 1000,//such as 30*1000=30 000ms currenttime =        +new Date ();        Step = (Current time-past time)/total number of seconds schedule = (currenttime-oldtime)/allms;        This.schedule = schedule;        This.drawall (schedule);           if (currenttime-oldtime >= allms) {//Redraw this.drawbackground (); This.drawprocess ();            This.drawanimate ();            This.drawinner ();            This.stroketext (0);        Clearinterval (timer); }}, 100);};/    /Draw All Countdown.prototype.drawAll = function (schedule) {schedule = Schedule >= 1? 1:schedule;    Let text = parseint (This.settings.time * (1-schedule)) + 1;    Clear Canvas this.ctx.clearRect (0, 0, this.settings.size, this.settings.size);    This.drawbackground ();    This.drawprocess ();    This.drawanimate ();    This.drawinner (); This.stroketext (text);};/    /object copy function extend (OBJ1,OBJ2) {for (let attr in Obj2) {obj1[attr] = obj2[attr]; }}

Iv. additional--canvas preparatory work

Canvas is not so iffy, it is nothing more than a H5 tag, just like any other HTML tag:

<canvas id= "Canvas" ></canvas>

Note It is best to set its width to canvas at the outset (if not set wide, the browser will default to the canvas size of 300, 100 pixels high), and cannot be set using CSS (will be stretched), it is recommended to write directly inside the canvas label:

<canvas id= "Canvas" width= "height=" ></canvas>

Canvas itself does not have any ability to draw, all the drawing work is done by JS. Usually we use getElementById to get the canvas to manipulate in JS (which means you have to set an ID for the canvas):

var c = document.getElementById ("canvas"); var ctx = C.getcontext ("2d");

1. Prepare the brush after you can start drawing, ring is actually a radius of different concentric circles, the center coordinate is (SIZE/2,SIZE/2), first draw a largest white background of the bottom circle, the radius is SIZE/2.

Let deg = math.pi/180;//Beginpath () can be used to isolate the effect of path rendering to prevent the previous effect from being contaminated. Ctx.beginpath ();//Tcx.arc (center x, center y, radius, starting angle, end angle, clockwise); Ctx.arc (SIZE/2, SIZE/2, SIZE/2, 0* deg, * deg, false); ctx. FillStyle = "#fff"; Ctx.fill (); Ctx.closepath ();

2. Start to draw the second yellow to hit the bottom circle, the center is also (SIZE/2,SIZE/2), but the radius is smaller than the white bottom circle 4px, so the radius of the Yellow bottom circle is (size/2-4)

Let deg = math.pi/180;//Beginpath () can be used to isolate the effect of path rendering to prevent the previous effect from being contaminated. Ctx.beginpath ();//Tcx.arc (center x, center y, radius, starting angle, end angle, shun counterclockwise); Ctx.arc (SIZE/2, SIZE/2, size/2-4, 0* deg, * deg, false); CT X.fillstyle = "#fff"; Ctx.fill (); Ctx.closepath ();

3. Start drawing the blue inner circle, the same as the Center (SIZE/2,SIZE/2), radius (size-23), and then add 4px white border.

Let deg = math.pi/180;//Beginpath () can be used to isolate the effect of path rendering to prevent the previous effect from being contaminated. Ctx.beginpath ();//Tcx.arc (center x, center y, radius, starting angle, end angle, clockwise); Ctx.arc (SIZE/2, SIZE/2, size/2-23, 0* deg, * deg, false); c Tx.fillstyle = "#fff"; Ctx.fill (); Ctx.closepath ();//white border ctx.linewidth = 4;ctx.strokestyle = #fff; Ctx.stroke ();

4. Draw text and center vertically

ctx.textalign = "center"; ctx.textbaseline = "middle"; ctx.fillstyle = "#fff";//Ctx.filltext (text, relative to the canvas's x-coordinate, relative to the canvas's y-coordinate) Ctx.filltext (SIZE/2, SIZE/2);

5. How do I make an animation? In fact, the process of painting a white circle, slowly covering the process of yellow progress bar, then the white circle is drawn out, this time the blue circle will be the white animated circle to cover, this time the final picture of the Blue circle is good.

Let deg = Math.pi/180;ctx.beginpath ();//Tcx.arc (center x, center y, radius, starting angle, end angle, clockwise); Ctx.arc (SIZE/2, SIZE/2, size/2-4, 0* D eg, deg, false); Ctx.fillstyle = "#fff"; Ctx.fill (); Ctx.closepath ();

6. A relatively simple painting process is complete, the next is to associate the animation and the number, using the current time-the beginning of time, in addition to the total time can be a key percentage, this percentage determines the number of changes, as well as the White animation circle drawing angle.

Countdown.prototype.countdown = function () {Let oldtime = +new Date ();////Past time: 1522136419291 timer = setinterval ( ) = = CurrentTime = +new Date ();//Current time: 1522136419393 let Allms = this.settings.time * 1000;//Total Time Hao         Seconds: such as 30*1000=30 000ms schedule = (currenttime-oldtime)/allms;//Draw percent: (1522136419393-1522136419291)/30000=0.0204        This.schedule = schedule;        This.drawall (schedule);            if (currenttime-oldtime >= allms) {//Redraw this.drawbackground ();            This.drawprocess ();            This.drawanimate ();            This.drawinner ();            This.stroketext (0);        Clearinterval (timer); }}, 10);};/    /Draw All Countdown.prototype.drawAll = function (schedule) {schedule = Schedule >= 1? 1:schedule;    Let text = parseint (This.settings.time * (1-schedule)) + 1;    Clear Canvas this.ctx.clearRect (0, 0, this.settings.size, this.settings.size);    This.drawbackground (); This.drawproceSS ();    This.drawanimate ();    This.drawinner (); This.stroketext (text);};/    /Draw progress bar Animation Countdown.prototype.drawAnimate = function () {//rotation angle let deg = math.pi/180;    Let V = schedule *, Startang = -90,//start Angle Endang = -90 + v;//End angle 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, FAL    SE);    This.ctx.fillStyle = This.settings.scheduleColor;    This.ctx.fill (); This.ctx.closePath ();};

Process-oriented version

/** * progress bar Animation */Countdown:function () {this.getsysteminfo (). Then (v =//Adaptive L Et 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 Tim E = MaxTime *, currenttime = +new Date, schedule = (currenttime-stime                    )/time;                    This.drew (schedule, maxtime, size);                            if (currenttime-stime >= time) {//Draw text This.setdata ({                        schedule:0});                    Clearinterval (temp);                };        }, 100);    });  },/** * draw */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});        Clear the canvas ctx.clearrect (0, 0, size, size);        Draw White bottom ctx.beginpath ();        Ctx.arc (R, R, r, 0 * deg, deg);        Ctx.fillstyle = ' Rgba (255,255,255,1) ';        Ctx.closepath ();        Ctx.fill ();        Draw Orange Ctx.beginpath ();        Ctx.arc (R, R, r-2, 0 * deg, deg);        Ctx.fillstyle = ' Rgba (248,200,80,1) ';        Ctx.closepath ();        Ctx.fill ();        Draw a white progress bar let V = schedule * 360;        Ctx.beginpath ();        Ctx.moveto (R, R);        Ctx.arc (R, R, R, -90 * deg, ( -90 + V) * deg);        Ctx.fillstyle = ' Rgba (255,255,255,1) ';        Ctx.closepath ();        Ctx.fill ();        Center Blue Bottom Ctx.beginpath (); Ctx.arc (R, R, R -0 * deg, deg);        Ctx.fillstyle = ' Rgba (90,140,220,1) ';        Ctx.closepath ();        Ctx.fill ();                Draw text Ctx.stroketext ();                Unified painting Ctx.draw (); },

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.