当前位置:网站首页>How to realize the center progress bar in wechat applet
How to realize the center progress bar in wechat applet
2022-06-30 21:59:00 【Yisu cloud】
How to realize the center progress bar in wechat applet
This article mainly introduces “ How to realize the center progress bar in wechat applet ” Knowledge about , Xiaobian shows you the operation process through practical cases , The operation method is simple and fast , Practical , Hope this article “ How to realize the center progress bar in wechat applet ” The article can help you solve problems .
One 、 Create project structure
Open wechat developer tool to create a project , newly build And pages At the same directory components, stay components Create a new directory in circle ,circle New China Component Name it circle, Automatically generated json、wxml、wxss、js 4 File . The structure is as follows :

Two 、 Write components
The first thing you need to do is json File for custom component declaration ( take component Field set to true, This set of files can be set as custom components ).
{"component": true}meanwhile , Still in wxml Write the component template in the file , stay wxss Add component styles... To the file , Here is the template and style of the circle progress bar , See the circular progress bar of wechat applet .
it is to be noted that canvas What you're drawing is px Unit , So here we use px Company ; among size It's based on canvas Diameter of the circle drawn , There is js It will be mentioned in .
In the component's wxml Can contain slot node , Used to host the... Provided by the component consumer wxml structure .
<!-- components/circle/circle.wxml --><view class="circle_box" > <canvas class="circle_bg" canvas-id="{{bg}}" ></canvas> <canvas class="circle_draw" canvas-id="{{draw}}" ></canvas> <slot></slot> </view>Be careful : In components wxss Should not use ID Selectors 、 Property selector and tag name selector .
/* components/circle/circle.wxss */.circle_box,.circle_draw{ position: relative; }.circle_bg{position: absolute;}To write js
In the custom component of js In file , Need to use Component() To register components , And provide the property definition of the component 、 Internal data and custom methods .
The property values and internal data of the component will be used for the component wxml Rendering of , among , Property values can be passed in from outside the component . Reference for more details Component Constructors .
/* components/circle/circle.js */Component({ …… methods: { /* id : canvas Unique identifier of the component canvas-id ,x : canvas Draw the radius of the circle , w : canvas Draw the width of the torus */ drawCircleBg: function (id, x, w) { // Set the size of the box outside the ring The width and height are equal to the ring diameter this.setData({ size: 2 * x }); // Use wx.createContext Get drawing context ctx Draw a background ring var ctx = wx.createCanvasContext(id) ctx.setLineWidth(w / 2); ctx.setStrokeStyle('#20183b'); ctx.setLineCap('round') ctx.beginPath();// Start a new path // Set an origin (x,y), The radius is r The path of the circle to the current path here x=y=r ctx.arc(x, x, x - w, 0, 2 * Math.PI, false); ctx.stroke();// Stroke the current path ctx.draw(); }, drawCircle: function (id, x, w, step) { // Use wx.createContext Get drawing context context Draw a colored progress bar circle var context = wx.createCanvasContext(id); // Set the gradient var gradient = context.createLinearGradient(2 * x, x, 0); gradient.addColorStop("0", "#2661DD"); gradient.addColorStop("0.5", "#40ED94"); gradient.addColorStop("1.0", "#5956CC"); context.setLineWidth(w); context.setStrokeStyle(gradient); context.setLineCap('round') context.beginPath();// Start a new path // step from 0 To 2 For a week context.arc(x, x, x - w, -Math.PI / 2, step * Math.PI - Math.PI / 2, false); context.stroke();// Stroke the current path context.draw() }, _runEvent() { // Trigger custom component event this.triggerEvent("runEvent") } }, ……})The custom component circular progress bar has been completed .
Use custom components
And now we have index Use custom component circular progress bar in .
One 、json Make a reference statement in the document
Before using registered custom components , The first The first thing to do is to json Make a reference statement in the document . At this time, you need to provide the tag name of each custom component and the corresponding custom component file path :
{ "usingComponents": { "circle": "/components/circle/circle" }}Two 、wxml Use custom components in files
such , On page wxml You can use custom components just like basic components . The node name is the tag name of the custom component , The node property is the property value passed to the component .
The node name is the tag name of the custom component :circle;
The node property is the property value passed to the component :bg,draw;
When a custom component triggers runEvent When an event is , call _runEvent Method .
<!--index.wxml--><view class="container"> <circle id='circle1' bg='circle_bg1' draw='circle_draw1' bind:runEvent="_runEvent" > <!-- This part of the content will be placed in the component <slot> Location --> <view class="circle_info" bindtap="changeTime"> <view class="circle_dot"></view> <text class='circle_txt'> {{txt}} </text> </view> </circle></view>For custom components wxml After the node structure is combined with the data , Will be inserted into the reference position . stay wxss to slot Add some styles to the content on the location .
/**index.wxss**//* Circle progress bar text */.circle_info{ position: absolute; width: 100%; left: 50%; top: 50%; transform: translate(-50%,-50%); display: flex; align-items: center; justify-content: center}.circle_dot{ width:16rpx; height: 16rpx; border-radius: 50%; background-color: #fb9126;} .circle_txt{ padding-left: 10rpx; color: #fff; font-size: 36rpx; letter-spacing: 2rpx;}3、 ... and 、js File to call the method in the custom component
stay wxml We use a data {{txt}}, We need to be in js Set it up in data, And then in onReady Use in selectComponent Select the component instance node .
//index.js data: { txt: " Matching ..." }, onReady: function () { // get circle Components this.circle = this.selectComponent("#circle1"); // Draw a background ring this.circle.drawCircleBg('circle_bg1', 100, 8) // Draw a colored circle this.circle.drawCircle('circle_draw1', 100, 8, 2); },The effect is as follows :
this.circle.drawCircle('circle_draw1', 100, 8, 0.5);
this.circle.drawCircle('circle_draw1', 100, 8, 1);
this.circle.drawCircle('circle_draw1', 100, 8, 2);
The next step is to write a timer method , Call every other time in the timer this.circle.drawCircle(id, x, w, step), By changing step To dynamically draw the torus .
1. stay data Set several initial values in
2. Define a timer method countInterval, Assume that every 100 millisecond count Increasing
+1, When count Increase to 100 It happens to be a circle when , Then change txt Value and clear the timer
3. stay onReady Call this timer method in
data: { txt: " Matching ...", count: 0,// Counter , The initial value is 0 maxCount: 100, // The steps required to draw a torus countTimer: null,// Timer , The initial value is null }, countInterval: function () { // Set the countdown Timer Assume that every 100 millisecond count Increasing +1, When count Increase to twice maxCount It happens to be a circle when ( step from 0 To 2 For a week ), Then change txt Value and clear the timer this.countTimer = setInterval(() => { if (this.data.count <= 2 * this.data.maxCount) { // Draw a colored circle progress bar this.circle.drawCircle('circle_draw1', 100, 8, this.data.count / this.data.maxCount) this.data.count++; } else { this.setData({ txt: " The match is successful " }); clearInterval(this.countTimer); } }, 100) }, onReady: function () { // get circle Components this.circle = this.selectComponent("#circle1"); // Draw a background ring this.circle.drawCircleBg('circle_bg1', 100, 8) // Draw a colored circle // this.circle.drawCircle('circle_draw1', 100, 8, 2); this.countInterval() },Final effect

Use the custom component again to count down
count It can be incremented , Of course, it can decrease . I'm not going to go over it here , Go straight to the code :
wxml
<circle id='circle'bg='circle_bg'draw='circle_draw'bind:runEvent="_runEvent" > <view class="circle_text" bindtap="changeTime"> <text class='circle_time'> {{time}} s</text></view></circle>wxss
/* Ring countdown */.circle_text{position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);}.circle_time{color: #fff;font-size: 32rpx;padding-left: 16rpx;}js
const app = getApp()Page({ …… stepInterval: function () { var n = this.data.num / 2 // Set the countdown Timer this.stepTimer = setInterval(() => { if (this.data.num >= 0) { this.data.step = this.data.num / n; this.circle.drawCircle('circle_draw', 40, 4, this.data.step)// Draw a colored circle progress bar if ((/(^[1-9]\d*$)/.test(this.data.num / 10))) { this.setData({ // When the time is an integer second Change time time: this.data.num / 10 }); } this.data.num--; } else { this.setData({ time: 0 }); } }, 100) }, changeTime: function () { clearInterval(this.stepTimer); this.setData({ num: 100 }); this.stepInterval() // Restart the countdown this._runEvent() // Trigger custom component event }, ……})Final effect

About “ How to realize the center progress bar in wechat applet ” That's all for , Thanks for reading . If you want to know more about the industry , You can pay attention to the Yisu cloud industry information channel , Xiaobian will update different knowledge points for you every day .
边栏推荐
- [introduction to MySQL] the first conversation · first time in the "database" Mainland
- Introduction and example of template method mode
- 京东与腾讯续签三年战略合作协议;起薪涨至26万元,韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条
- Reading notes of Clickhouse principle analysis and Application Practice (3)
- Pytorch quantitative practice (1)
- 激发新动能 多地发力数字经济
- 阿婆做的臭豆腐
- 5g demand in smart medicine
- Do a scrollbar thinking
- 模板方法模式介绍与示例
猜你喜欢

AKK菌——下一代有益菌

Arcmap|assign values to different categories of IDS with the field calculator

Uniapp routing uni simple router

京东与腾讯续签三年战略合作协议;起薪涨至26万元,韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条

Five years after graduation, I wondered if I would still be so anxious if I hadn't taken the test

Clickhouse native monitoring item, system table description

Nacos部署及使用

About, Qianxin detects code vulnerabilities and XSS series solves them

Introduction to go web programming: a probe into the excellent test library gocovey

Neurotransmetteurs excitateurs - glutamate et santé cérébrale
随机推荐
Analysis of doctor Aifen's incident
Arcmap|assign values to different categories of IDS with the field calculator
A comprehensive understanding of gout: symptoms, risk factors, pathogenesis and management
1-1 数据库的基本概念
WinDbg debugging tool introduction
Do machine learning jobs require graduate students?
About, Qianxin detects code vulnerabilities and XSS series solves them
VIM common shortcut keys
Zhoushaojian, rare
1-15 nodemon
Summary of errors reported when using YML file to migrate CONDA environment
Uniapp routing uni simple router
1-7 path module
Reading notes of Clickhouse principle analysis and Application Practice (1)
ssh 默认端口不是22时的一些问题
Is machine learning suitable for girls?
Reading notes of Clickhouse principle analysis and Application Practice (3)
Vite2 is compatible with lower versions of chrome (such as Sogou 80). Some grammars requiring higher versions are processed through polyfills
Document layout analysis: a comprehensive survey 2019 paper learning summary
《安富莱嵌入式周报》第270期:2022.06.13--2022.06.19