当前位置:网站首页>Summer Challenge harmonyos canvas realize clock

Summer Challenge harmonyos canvas realize clock

2022-07-01 15:53:00 51CTO

author : Zheng Yao

  This article is participating in the starlight project 3.0– Summer Challenge

Preface

Studying recently HarmonyOS Relevant stuff , Read a lot of online canvas Realize the clock , Now I also want to write a story about HarmonyOS Your clock .

Project description

Tool version :DevEco Studio 3.0 Beta3

SDK edition ;3.1.5.5

It mainly uses knowledge :canvas js

Effect display

# Summer Challenge # HarmonyOS canvas Realize the clock _ Hongmeng

Implementation steps

1. On the page index.hml Define a canvas Elements

<div class="container">
    <canvas ref="clock" style="width: 600px; height:600px; background-color:#5a5a5a "></canvas>
</div

     
  • 1.
  • 2.
  • 3.

2. Need to be in index.js data Two variables are defined in to store the target element and draw 2d

export default {
  data: {
      c:'',
      ctx:''
  }
 }

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

3. Need to be in onShow Get the target element in the life cycle and draw 2d

onShow(){
  this.el = this.$refs.clock;
        // obtain canvas Drawing context 
  this.ctx = this.el.getContext('2d');
  this.initData()
},

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

4. Define an initialization function initData(), Call the draw function

  initData:function(){
    this.updateClock(this.ctx)
  },

     
  • 1.
  • 2.
  • 3.

5. Draw function clock function

5.1 First draw the largest circle on the outside

 drawPanel:function(ctx){
      ctx.beginPath()  // Start 
      ctx.arc(300, 300, 200, 0, Math.PI * 2) // Draw the arc path 
      ctx.fillStyle = 'white' // Fill color 
      ctx.fill() // fill 
      ctx.closePath()  // closed 
    },

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

At this time, the page is so long :

# Summer Challenge # HarmonyOS canvas Realize the clock _ Hongmeng _02

5.2 Draw time ( when ) scale (12 Hour scale )

  hourCalibration:function(ctx){
        var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; // Define the number of the scale 
        ctx.beginPath(); // Start 
        ctx.translate(300, 300) // Move the origin of the current coordinate system 
        ctx.font = '30px bold' // Size of text 
        ctx.textAlign = "center"; //  Writing in the middle 
        ctx.textBaseline = "middle"; //  Set the horizontal alignment in text drawing   Is the middle of the text block 
        ctx.fillStyle = "black"; //  Fill color 
        for (var i = 0; i < arr.length; i++) {
// Draw fill text 
          ctx.fillText(
            arr[i],
            168 * Math.cos(((i * 30 - 60) * Math.PI) / 180),
            168 * Math.sin(((i * 30 - 60) * Math.PI) / 180)
          );
        }
        ctx.closePath(); //  end 
    },

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

Now the page :

# Summer Challenge # HarmonyOS canvas Realize the clock _ Hongmeng _03

5.3 Draw a small dot in the center

 centerDot:function(ctx){
        ctx.beginPath(); //  Start 
        ctx.arc(0, 0, 8, 0, 2 * Math.PI); // Draw the arc path 
        ctx.fill(); // Fill the closed path 
        ctx.beginPath(); // Start 
        ctx.fillStyle = "white";
        ctx.arc(0, 0, 5, 0, 2 * Math.PI); // Draw the arc path 
        ctx.fill();// Fill the closed path 
    },

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

At this time, the page is so long :

# Summer Challenge # HarmonyOS canvas Realize the clock _canvas_04

5.4 Get time and convert it into Beijing time

At this time, you need to get the local time of the current system , I have a little trouble here , Hongmeng developer tool new Date() The obtained time is Greenwich mean time , Now we use Beijing time , You need to write a function to convert time , The conversion function is getTimeStamp()

 getTimeStamp:function(){
    var zoneOffset = 8;
    // Calculate the time difference , And convert to milliseconds :
    var offset2 = new Date().getTimezoneOffset()* 60 * 1000;
    // Calculate the time when it appears :
    var nowDate2 = new Date().getTime();
    // At this time, the time of Dongba District 
    var currentZoneDate = new Date(nowDate2 + offset2 + zoneOffset*60*60*1000);
    return currentZoneDate;
}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

Get the current Beijing time :

// Modification time   The default is Greenwich mean time   You need to convert time into Beijing time 
var date = this.getTimeStamp(new Date())
// Get the current hour 
var hours = date.getHours()
console.log(hours+'hours')
// Get the current minute 
var minutes = date.getMinutes()
console.log(minutes+'minutes')
// Get current seconds 
var seconds = date.getSeconds()
console.log(seconds+'seconds')

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

5.5 Draw the pointer of the clock

  hourHand:function(ctx,hours, minutes){
        var radius =
          ((2 * Math.PI) / 12) * hours + (((1 / 6) * Math.PI) / 60) * minutes;
        ctx.save();//  Save current state , In order to return to the original state after rotation .
        ctx.beginPath(); // Start 
        ctx.lineWidth = 8;         //  Needle width 
        ctx.lineCap = "round";          //  The needle is rounded 
        ctx.strokeStyle = "green"; // Color of needle 
        ctx.rotate(radius); //  rotate 
        ctx.moveTo(0, 0);
        ctx.lineTo(0, -90);
        ctx.stroke();
        ctx.closePath() //  end 
        //  Return to the saved state 
        ctx.restore();
    },

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

At this time, the page is so long :

# Summer Challenge # HarmonyOS canvas Realize the clock _ The clock _05

5.6 Draw the pointer of the minute hand

 minuteHand:function(ctx,minutes){
        2 * Math.PI;
        var radius = ((2 * Math.PI) / 60) * minutes;
        ctx.save(); //  Save current state , In order to return to the original state after rotation .
        ctx.beginPath(); // Start 
        ctx.lineWidth = 4; //  Needle width 
        ctx.lineCap = "round"; // The needle is rounded 
        ctx.strokeStyle = "black";
        ctx.rotate(radius); // rotate 
        ctx.moveTo(0, 0);
        ctx.lineTo(0, -110);
        ctx.stroke(); // Draw a contour circle 
        ctx.closePath() // end 
        ctx.restore();
    },

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

At this time, the page looks like this :

# Summer Challenge # HarmonyOS canvas Realize the clock _ Hongmeng _06

5.7 Draw a second hand

secondHand:function(ctx,seconds) {
        var radius = ((2 * Math.PI) / 60) * seconds;
        ctx.save(); //  Save current state , In order to return to the original state after rotation .
        ctx.beginPath(); // Start 
        ctx.lineWidth = 2; //  Needle width 
        ctx.lineCap = "round"; // The needle is rounded 
        ctx.strokeStyle = "red";
        ctx.rotate(radius); // rotate 
        ctx.moveTo(0, 0);
        ctx.lineTo(0, -140);
        ctx.stroke();// Draw a contour circle 
        ctx.closePath() // end 
        ctx.restore();
      },

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

At this time, the page looks like this :

# Summer Challenge # HarmonyOS canvas Realize the clock _ China soft International _07

5.8 Finally, we need to write an update function to call all painting functions and get the corresponding Beijing time in the update function :

updateClock:function(ctx){
    var time = this.getTimeStamp(new Date())
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    ctx.save();
    this.drawPanel(this.ctx);
    this.hourCalibration(this.ctx);
    this.secondHand(this.ctx,seconds);
    this.minuteHand(this.ctx,minutes);
    this.hourHand(this.ctx,hours, minutes);
    this.centerDot(this.ctx)
    ctx.closePath();
    ctx.restore();
}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

6. The last step is to make the clock turn

So you need to be in initData Write a timer in the function and execute the drawing function every second : The final picture is as shown in the first picture above

initData:function(){
        //  The timer refreshes every minute 
        let timer = setInterval(()=>{
        this.ctx.clearRect(0, 0, 600, 600); // Delete the drawing content in the specified area .
        this.updateClock(this.ctx)
        },1000)
    },

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

summary :

That's all canvas All the steps of drawing a clock . The most important thing is to get the time correctly ( Beijing time. ) But I found in the editor new Date() The time of arrival is eight hours away from our Beijing time , Only under the reminder of a colleague did I know that the obtained time was Greenwich mean time , Then we need to convert this Greenwich mean time into Beijing time , I found a transformation method on the Internet, and finally the transformation was successful .

For more original content, please pay attention to :  China soft International HarmonyOS Technical team

Beginner to master 、 Skills to cases , Systematic sharing HarmonyOS Development technology , Welcome to contribute and subscribe , Let's move forward hand in hand to build Hongmeng ecology .

  Want to know more about open source , Please visit :

 51CTO Open source basic software community

 https://ost.51cto.com/#bkwz

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011533067665.html