既然已经2020年了,ECMAScript 都出了2019版了。当然要与时俱进
函数写法教程
我自己写的class封装类 知识点:
1.ES6语法
2.canvas知识
效果
代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body style="background-color: #A8D8EC;">
<div id="canvas-warp" style="display: block; margin: 200px auto;" >
<canvas id="canvas" width="200" height="200" style="margin: 0 auto;display: block;background-color: #fff;border-radius: 50%" >
</canvas>
</div>
</body>
<script>
class CanvasClock{
constructor(cav,x,y,size){//需要的canvasdom,以及画在那个位置的x,y轴,以及大小;
this.cav = cav;
this.x = x;
this.y = y;
this.size = size;
}
drawBackground (){
var r = 100*this.size;
var ctx = this.cav.getContext('2d');
ctx.clearRect(0,0,this.cav.height,this.cav.width);//清除画布上的内容,不用担心性能问题,canvas动画都是用直接清除画布再画的方法
var numbers = [3,4,5,6,7,8,9,10,11,12,1,2];
//ctx.clearRect(0,0,r*this.x,r*this.y);
ctx.save();
ctx.beginPath();
ctx.translate(this.x,this.y);
ctx.lineWidth=this.size*10;
ctx.arc(0,0,r-5,0,2*Math.PI);
ctx.stroke();
ctx.font = '18px Arial';
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
numbers.forEach(function(item,i){
let rad = 2*Math.PI / 12 *i;
let x =Math.cos(rad) * (r-30);
let y =Math.sin(rad) * (r-30);
ctx.fillText(item,x,y);
});
for(let i=0;i<60;i++){
let rad = 2* Math.PI /60 *i;
let x =Math.cos(rad) * (r-18);
let y =Math.sin(rad) * (r-18);
ctx.beginPath();
if(i%5==0){
ctx.fillStyle ='#000';
ctx.arc(x,y,2,0,2*Math.PI,false);
}else{
ctx.fillStyle ='#333';
ctx.arc(x,y,1,0,2*Math.PI,false);
}
ctx.fill();
}
ctx.restore();
}
drawDot(){
var r = 100*this.size;
var ctx = this.cav.getContext('2d');
ctx.save();
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.arc(0,0,3*this.size,0,2*Math.PI,false)
ctx.fill();
ctx.restore();
}
drawHour(hour,min){
var r = 100*this.size;
var ctx = this.cav.getContext('2d');
ctx.save();
ctx.beginPath();
ctx.translate(this.x,this.y);
let rad = 2*Math.PI / 12 *hour;
let minrad = 1/6*Math.PI /60 *min;
ctx.rotate(rad+minrad);
ctx.lineWidth = 6;
ctx.lineCap = 'round';
ctx.moveTo(0,10);
ctx.lineTo(0,-r/2+2);
ctx.stroke();
ctx.restore();
}
drawMin(min){
var r = 100*this.size;
var ctx = this.cav.getContext('2d');
ctx.save();
ctx.beginPath();
ctx.translate(this.x,this.y);
let rad = 2*Math.PI / 60 *min;
ctx.rotate(rad);
ctx.lineWidth = 4;
ctx.moveTo(0,13);
ctx.lineTo(0,-r/2-15);
ctx.stroke();
ctx.restore();
}
drawSec(sec){
var r = 100*this.size;
var ctx = this.cav.getContext('2d');
ctx.save();
ctx.beginPath();
ctx.translate(this.x,this.y);
ctx.strokeStyle ="#F4606C"
let rad = 2*Math.PI / 60 *sec;
ctx.rotate(rad);
ctx.lineWidth = 4;
ctx.moveTo(0,13);
ctx.lineTo(0,-r/2-35);
ctx.stroke();
ctx.restore();
}
draw(){
this.timer = setInterval( () => {
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
this.drawBackground();
this.drawHour(hour,min);
this.drawMin(min);
this.drawSec(sec);
this.drawDot();
}, 1000)
}
}
var clockOne = new CanvasClock(document.getElementById("canvas"),100,100,1);
clockOne.draw();
</script>
</html>