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

Interpretation of the module for load balancing using nginx

Table of contents Two modules for using nginx for...

SQL implementation of LeetCode (175. Joining two tables)

[LeetCode] 175.Combine Two Tables Table: Person +...

Sample code for changing the color of a png image through a CSS3 filter

This method uses the drop-shadow filter in CSS3 t...

Do you know the common MySQL design errors?

Thanks to the development of the Internet, we can...

Introduction and installation of MySQL Shell

Table of contents 01 ReplicaSet Architecture 02 I...

Vue uses custom instructions to add watermarks to the bottom of the page

Project Scenario Add a custom watermark to the en...

How to clear default styles and set common styles in CSS

CSS Clear Default Styles The usual clear default ...

How to set the width attribute to the style of the span tag

If you directly set the width attribute to the sty...

Nodejs implements intranet penetration service

Table of contents 1. Proxy in LAN 2. Intranet pen...

How to use Zen coding in Dreamweaver

After I published my last article “Zen Coding: A Q...

Docker packages the local image and restores it to other machines

1. Use docker images to view all the image files ...

IDEA graphic tutorial on configuring Tomcat server and publishing web projects

1. After creating the web project, you now need t...

CSS web page responsive layout to automatically adapt to PC/Pad/Phone devices

Preface There are many devices nowadays, includin...

Analysis of Mysql transaction characteristics and level principles

1. What is a transaction? A database transaction ...