WeChat applet uses canvas to draw clocks

WeChat applet uses canvas to draw clocks

This article shares the specific code of using canvas to draw a clock in WeChat applet for your reference. The specific content is as follows

Analog clock

Use canvas to draw a clock to realize the function of analog clock. The clock time is consistent with the system time. The scale converts the 24-hour system to the 12-hour system. It is necessary to draw the center circle, outer circle, minute hand, hour hand, and second hand separately.

The effect diagram is as follows:

The code is as follows:

index.wxml

<canvas canvas-id="myCanvas" class="mycanvas"></canvas>

index.wxss

/**index.wxss**/
.mycanvas {
  width: 100%;
  height: 100%;
  position: fixed;
}

index.js

Page({
  width: 0, //window width height: 0, //window height onLoad: function () {
    // Get system information wx.getSystemInfo({
      // Get system information successfully, save the obtained width and height of the system window success: res => {
        // console.log(res)
        this.width = res.windowWidth
        this.height = res.windowHeight
        }
      })
    },
  timer: null, //timer onReady: function(){
    //Create ctx instance var ctx = wx.createCanvasContext('myCanvas')
    //Convert the angle to radians for later use //Calculation formula: radians = angle*Math.PI / 180
    const D6 = 6 * Math.PI / 180
     const D30 = 30 * Math.PI / 180
     const D90 = 90 * Math.PI / 180
     // Get the width and height values ​​var width = this.width, height = this.height
     // Calculate the dial radius and leave 30px margin var radius = width / 2 -30
     // Draw once per second draw()
     this.timer = setInterval(draw, 1000)
     //Drawing function function draw(){
       // Set the axis origin to the center of the window ctx.translate(width / 2, height / 2)
       // Draw the dial drawClock(ctx,radius)
       // Draw the pointer drawHand(ctx, radius)
       //Execute drawing ctx.draw()
   }
  
    // Draw the dial function drawClock(ctx, radius){
      // Draw a big circle // The radius of the big circle is radius and the line thickness is 2px
      ctx.setLineWidth(2) //Set line thickness ctx.beginPath() //Start a new path ctx.arc(0, 0, radius, 0, 2 * Math.PI, true)
      ctx.stroke() //Draw lines //Draw concentric circles //The radius of the center circle is 8px and the line thickness is 1px
      ctx.setLineWidth(1) //Set line thickness ctx.beginPath() //Start a new path ctx.arc(0, 0, 8, 0, 2 * Math.PI, true)
      ctx.stroke() //Draw a line // Draw a large dial with a line thickness of 5px
      ctx.setLineWidth(5)
      for (var i = 0; i < 12; ++i){
        // Clockwise with the origin as the center (the rotation angles will be superimposed if multiple calls are made)
        // The large dial needs to draw 12 lines, representing 12 hours, and rotates 30 degrees each time ctx.rotate(D30) // 360 / 12 = 30
        ctx.beginPath()
        ctx.moveTo(radius, 0)
        ctx.moveTo(radius - 15, 0) //Large scale length 15px
        ctx.stroke()
      }
      // Draw a small dial with a line thickness of 1px
      ctx.setLineWidth(1)
      for(var i = 0; i < 60; ++i){
        // The small dial needs to draw 60 lines, representing 60 minutes or 60 seconds, and rotates 6 degrees each time ctx.rotate(D6)
        ctx.beginPath()
        ctx.moveTo(radius, 0)
        ctx.lineTo(radius - 10, 0) //Small dial length 10px
        ctx.stroke()
      }
      //Draw text ctx.setFontSize(20) //Font size ctx.textBaseline = 'middle' // Vertically center the text // Calculate the radius r of the text from the center of the dial
      var r = radius - 30
      for(var i = 1; i <= 12; ++i){
        // Calculate text coordinates using trigonometric functions var x = r * Math.cos(D30 * i - D90)
        var y = r * Math.sin(D30 * i - D90)
        if(i > 10){ // Adjust the positions of 11 and 12 // Draw text on the canvas fillText(text, upper left corner x coordinate, upper left corner y coordinate)
          ctx.fillText(i, x - 12, y)
        } else {
          ctx.fillText(i, x-6, y)
        }
      }
    }
    //Draw the pointer function drawHand(ctx, radius){
      var t = new Date() // Get the current time var h = t.getHours() //Hours var m = t.getMinutes() //Minutes var s = t.getSeconds() //Seconds h = h > 12 ? h -12 :h //Convert 24-hour system to 12-hour system //The time starts at 3 o'clock and rotates 90 degrees counterclockwise to point to 12 o'clock ctx.rotate(-D90)
      //Draw the hour hand ctx.save() //Record the rotation status // Calculate the scale pointed by the hour hand // 30 degrees * h can be used to calculate the rotation angle of each hour // If the time is not an hour, you need to use h + m / 60 + s / 3600 to calculate the exact offset ctx.rotate(D30 * (h + m / 60 + s / 3600))
      ctx.setLineWidth(6)
      ctx.beginPath()
      ctx.moveTo(-20, 0)
      ctx.lineTo(radius / 2.6, 0)
      ctx.stroke()
      ctx.restore()
      // Draw the minute hand ctx.save()
      ctx.rotate(D6 * (m + s / 60))
      ctx.setLineWidth(4)
      ctx.beginPath()
      ctx.moveTo(-20, 0)
      ctx.lineTo(radius / 1.8, 0)
      ctx.stroke()
      ctx.restore()
      //Draw the second hand ctx.save()
      ctx.rotate(D6 * s)
      ctx.setLineWidth(2)
      ctx.beginPath()
      ctx.moveTo(-20, 0)
      ctx.lineTo(radius / 1.6, 0)
      ctx.stroke()
      ctx.restore() 
    } 
  }
})

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • WeChat Mini Program Canvas Dynamic Clock
  • WeChat Mini Program Introduction: Drawing a Clock
  • JS draws WeChat applet canvas clock

<<:  How to deal with time zone issues in Docker

>>:  In-depth explanation of the locking mechanism in MySQL

Recommend

Bootstrap 3.0 study notes grid system case

Preface In the previous article, we mainly learne...

Implementation of fastdfs+nginx cluster construction

1. Introduction to fastdfs 1. What is fastdfs Fas...

js implements shopping cart addition and subtraction and price calculation

This article example shares the specific code of ...

Detailed explanation of the command mode in Javascript practice

Table of contents definition structure Examples C...

Implementation of WeChat applet message push in Nodejs

Select or create a subscription message template ...

Detailed explanation of some settings for Table adaptation and overflow

1. Two properties of table reset: ①border-collaps...

Continuous delivery using Jenkins and Docker under Docker

1. What is Continuous Delivery The software produ...

JavaScript Basics: Scope

Table of contents Scope Global Scope Function Sco...

Summary of some of my frequently used Linux commands

I worked in operations and maintenance for two ye...

How to export mysql table structure to excel

The requirements are as follows Export the table ...

What does mysql database do?

MySQL is a relational database management system....

MySQL data migration using MySQLdump command

The advantages of this solution are simplicity an...

Learn more about MySQL indexes

1. Indexing principle Indexes are used to quickly...