使用js和canvas写一个时钟,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
<!DOCTYPE html>` < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Document</ title > </ head > < body > < canvas id = 'canvas' width = '600' height = '600' style = "border: 1px solid red;" ></ canvas > < script > /** @type {HTMLCanvasElement} */ let canvas = document.querySelector("#canvas"); let ctx = canvas.getContext("2d"); let deg = Math.PI / 180; let HourR = 100; let MinutesR = 135; let SecondsR = 170; setInterval(function () { canvas.width = canvas.width; ctx.arc(300, 300, 200, 0, Math.PI * 2) ctx.fillStyle = 'rgba(10,100,30,0.2)' ctx.strokeStyle = 'red' //获取当前时间 let dt = new Date() let Hour = dt.getHours() let Minutes = dt.getMinutes() let Seconds = dt.getSeconds() //时钟 ctx.moveTo(300, 300); let xx = HourR * (Math.sin(Hour * 30 * deg)) let yy = HourR * (Math.cos(Hour * 30 * deg)) ctx.lineTo((300 + xx), (300 - yy)) //分钟和秒钟 function move(time, R) { ctx.moveTo(300, 300); xx = R * (Math.sin(time * 6 * deg)) yy = R * (Math.cos(time * 6 * deg)) ctx.lineTo((300 + xx), (300 - yy)) } //小时指针 for (let m = 0; m < 12 ; m++) { let xx = 190 * (Math.sin(m * 30 * deg)) let yy = 190 * (Math.cos(m * 30 * deg)) let xx1 = 200 * (Math.sin(m * 30 * deg)) let yy1 = 200 * (Math.cos(m * 30 * deg)) ctx.moveTo((300 + xx), (300 - yy)); ctx.lineTo((300 + xx1), (300 - yy1)) } move(Seconds, SecondsR) move(Minutes, MinutesR) ctx.fill() ctx.stroke() }, 1000) </script> </ body > </ html > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/HaiRong_21/article/details/108448368