概述
更多Canvas实例可以看GitHub,不定时更新:https://github.com/xiangshuo1992/canvas-demo
在学习了老师的课程之后,自己实现了一遍,同时写了一个面向对象的版本。
Canvas时钟效果-函数编程
Canvas时钟效果-面向对象版
本文效果可以直接看codepen效果
HTML
<div>
<canvas id="clock"></canvas>
<canvas id="clock2"></canvas>
<canvas id="clock3"></canvas>
</div>
CSS
div {
text-align: center;
margin-top: 250px;
}
JS Clock对象
/**
* 时钟构造函数(类)
*
* @param string id
* @param object config
*/
function Clock(id, config) {
this.canvas = document.getElementById(id);
this.context = this.canvas.getContext('2d');
//默认配置参数
this.config = {};
this.init(config);
};
/**
* 初始化方法
*
* @param object config
*/
Clock.prototype.init = function (config) {
//配置参数合并
for (const attr in config) {
this.config[attr] = config[attr];
}
//时钟走起来
this.draw();
};
/**
* 画钟表边框
*/
Clock.prototype.drawClockBorder = function () {};
/**
* 写钟表数字
*/
Clock.prototype.drawNumber = function () {};
/**
* 画刻度点
*/
Clock.prototype.drawScale = function () {};
/**
* 画时针
*/
Clock.prototype.drawHour = function (hour, minute) {};
/**
* 画分针
*/
Clock.prototype.drawMinute = function (minute) {};
/**
* 画秒针
*/
Clock.prototype.drawSecond = function (second) {};
/**
* 画固定点(螺丝)
*/
Clock.prototype.drawDot = function () {};
/**
* 时间走起来
*/
Clock.prototype.draw = function () {
let context = this.context;
context.clearRect(0, 0, this.config.width, this.config.height);
let now = new Date();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
this.drawClockBorder();
this.drawNumber();
this.drawScale();
this.drawHour(hour, minute);
this.drawMinute(minute);
this.drawSecond(second);
this.drawDot();
context.restore();
//用bind()绑定this对象
setInterval(this.draw.bind(this), 1000);
};
JS 应用实例化对象
//实例化一个Clock对象
// 默认配置
let clock = new Clock('clock');
具体详细代码大家可以看上面链接的源码。
抛开时钟的实现原理,面向对象的写法里有两点值得注意
关键点一
梳理对象的可配置参数及方法,设置默认配置参数,然后将用户配置的参数与默认参数合并
for (const attr in config) {
this.config[attr] = config[attr];
}
这是拷贝对象的方式,在JQ中,也是类似的原理,当然具体过程更复杂,添加了更多的判断。
$.extend(obj1,boj2);
关键点二
循环调用draw函数时,会出现this指向问题,这里通过bind()方法改变当前函数的this指向。
setInterval(this.draw.bind(this), 1000);
其他的大家直接看源码吧。
参考来源:慕课网视频教程-Canvas绘制时钟