class Clock {
constructor() {
this.canvas = document.querySelector('#canvas')
this.ctx = this.canvas.getContext('2d')
this.margin = 30
this.fontSize = 20
this.center = {
x: canvas.width / 2,
y: canvas.height / 2
}
this.init()
}
init() {
this.canvas.addEventListener('mousemove',function(e){
let can = this.canvas.getBoundingClintRect()
console.log(e.pageX,e.pageY,'e',can)
})
}
run() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.drawCircle()
this.drawNums()
this.drawCenter()
this.drawSecond()
this.minutes()
this.hour()
}
drawCircle() {
this.ctx.beginPath()
this.ctx.arc(this.center.x, this.center.y, this.canvas.width / 2 - this.margin, 0, 2 * Math.PI)
this.ctx.stroke()
}
drawNums() {
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let r = this.canvas.width / 2 - this.margin - this.fontSize
let angle = Math.PI * 2 / 12
arr.forEach(item => {
this.ctx.beginPath()
this.ctx.font = `${this.fontSize}px Arial`
let textWith = this.ctx.measureText(item).width
let x = Math.sin(angle * item) * r + this.canvas.width / 2 - textWith / 2
let y = this.canvas.height / 2 - Math.cos(angle * item) * r + this.fontSize / 2
this.ctx.fillText(item, x, y)
})
}
drawCenter() {
this.ctx.beginPath()
this.ctx.arc(this.canvas.width / 2, this.canvas.height / 2, 5, 0, 2 * Math.PI)
this.ctx.fill();
}
drawSecond() {
this.ctx.beginPath()
this.ctx.moveTo(this.center.x, this.center.y)
let date = new Date()
let time = date.getSeconds()
let angle = Math.PI * 2 / 60
let r = this.canvas.width / 2 - this.margin - this.fontSize - this.margin
let x = Math.sin(angle * time) * r + this.canvas.width / 2
let y = this.canvas.height / 2 - Math.cos(angle * time) * r
this.ctx.lineTo(x, y)
this.ctx.stroke()
}
minutes() {
this.ctx.beginPath()
this.ctx.moveTo(this.center.x, this.center.y)
let date = new Date()
let time = date.getMinutes()
let angle = Math.PI * 2 / 60
let r = this.canvas.width / 2 - this.margin - this.fontSize - this.margin * 2
let x = Math.sin(angle * time) * r + this.canvas.width / 2
let y = this.canvas.height / 2 - Math.cos(angle * time) * r
this.ctx.lineTo(x, y)
this.ctx.stroke()
}
hour() {
this.ctx.beginPath()
this.ctx.moveTo(this.center.x, this.center.y)
let date = new Date()
let time = date.getHours()
let angle = Math.PI * 2 / 12
let r = this.canvas.width / 2 - this.margin - this.fontSize - this.margin * 3
let x = Math.sin(angle * time) * r + this.canvas.width / 2
let y = this.canvas.height / 2 - Math.cos(angle * time) * r
this.ctx.lineTo(x, y)
this.ctx.stroke()
}
}
let clock = new Clock()
setInterval(() => {
clock.run()
}, 1000)
canvas 绘制时钟
最新推荐文章于 2022-11-08 22:38:02 发布