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

Introduction to fourteen cases of SQL database

Data Sheet /* Navicat SQLite Data Transfer Source...

JS 9 Promise Interview Questions

Table of contents 1. Multiple .catch 2. Multiple ...

How to run postgreSQL with docker

1. Install Docker. Reference URL: Docker Getting ...

A brief discussion on CSS blocking merging and other effects

Non-orthogonal margins When margin is used, it wi...

Introduction to the functions and usage of value and name attributes in Html

1. The value used in the button refers to the text...

Solution to the MySQL server has gone away error

MySQL server has gone away issue in PHP 1. Backgr...

Use Docker Compose to quickly deploy ELK (tested and effective)

Table of contents 1. Overview 1.1 Definition 1.2 ...

WeChat applet implements user login module server construction

I chose node.js to build the server. Friends who ...

ReactRouter implementation

ReactRouter implementation ReactRouter is the cor...

CSS controls the spacing between words through the letter-spacing property

letter-spacing property : Increase or decrease th...

Convert psd cut image to div+css format

PSD to div css web page cutting example Step 1: F...

CSS multi-column layout solution

1. Fixed width + adaptive Expected effect: fixed ...

Mysql some complex sql statements (query and delete duplicate rows)

1. Find duplicate rows SELECT * FROM blog_user_re...