附图
原理
首先通过js获取当前系统时间并建立一个数组将获取到的时间中的时分秒解析出来保存在数组内;
var time=new Date();
//time_a数组用于保存时分秒数据
var time_a =[time.getHours(),time.getMinutes(),time.getSeconds()];
其次就是canvas作图操作了,先创建一个画布,对其进行线性渐变,字体颜色设置等操作,最后通过canvas中的strokeText()方法将时间数组传入其中,并设置一秒刷新一次即可得到上述效果。代码如下,仅供参考学习。
注:采用jQuery纯属个人喜好,此项目jQuery用处不大,可自行用js代码代替。
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery.js"></script>
<script src="js/8_13.js"></script>
<style type="text/css" rel="stylesheet">
canvas{
background:#0C0C0C;
display: block;
margin:0 auto;
}
</style>
</head>
<body>
<canvas id="con" width="1000" height="600">
您的浏览器不支持canvas
</canvas>
</body>
</html>
JS代码:
$(function () {
var a = $("#con")[0];//获取canvas对象
var cxt = a.getContext('2d');
function play(){
var time=new Date();
//time_a数组用于保存时分秒数据
var time_a =[time.getHours(),time.getMinutes(),time.getSeconds()];
cxt.clearRect(0,0,1000,600);//清空画布,防止内容重叠
cxt.beginPath();
cxt.font='80px Arial';//设置字体大小和字体样式
cxt.lineWidth=2;//设置画线粗细
var grd = cxt.createLinearGradient(60,0,200,0); //横向渐变
grd.addColorStop(0,'red');
grd.addColorStop(0.5,'green');
grd.addColorStop(1,'blue');
cxt.strokeStyle=grd;
cxt.strokeText(time_a[0]+':'+time_a[1]+':'+time_a[2],60,100);
cxt.closePath();
}
play();
setInterval(play,1000);//每一秒刷新一次
});