近来学了一些canvas的基础操作,例如画线段、矩形、圆、字体、添加图片、渐变等等操作,便利用画布画了个时钟来练习一下,代码以及图片如下:
时钟图:
代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#cvs{
display: block;
margin: 0 auto;
border-radius: 30px;
background: #6F917D;
}
</style>
</head>
<body>
<canvas id="cvs" width="800" height="600"></canvas>
<script>
function clock () {
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
// 清除画布内容
ctx.clearRect(0,0,800,600);
// 获取时间
var dates = new Date();
var h = dates.getHours();
var min = dates.getMinutes();
var sec = dates.getSeconds();
var times = h + ':' + min;
h += min/60;
min += sec/60;
//设置表盘,渐变方法的参数1,2雨4,5分别为两个圆的圆心,参数3,6分别为两个圆的半径
var g1 = ctx.createRadialGradient(400, 300, 0, 400, 300, 150);
//设置两个渐变色的参数
g1.addColorStop(0, "#fcfcfc");
g1.addColorStop(1, "#808080");
// 画表盘和表心两圆
ctx.beginPath();
ctx.lineWidth = 8;
ctx.arc(400,300,150,0,2*Math.PI,true);
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.closePath();
ctx.fillStyle = g1;
ctx.fill();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.arc(400,300,10,0,2*Math.PI,true);
ctx.closePath();
ctx.fillStyle = 'yellow';
ctx.fill();
// 表盘分钟刻度线
for (var i=0; i<60; i++) {
ctx.save(); // 保存状态
ctx.translate(400, 300);
ctx.rotate(Math.PI/30 * i);
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.fillRect(0, -150, 2, 10);
ctx.closePath();
ctx.restore(); // 恢复原始状态
}
// 表盘时钟刻度线
for (var i = 0; i<12; i++) {
ctx.save();
ctx.translate(400, 300);
ctx.rotate(Math.PI/6 * i);
ctx.beginPath();
ctx.fillStyle = 'black';
ctx.fillRect(0, -150, 2, 15);
ctx.closePath();
ctx.restore();
}
// 表盘时针
ctx.save();
ctx.translate(400, 300);
ctx.rotate(Math.PI/6 * h);
ctx.beginPath();
ctx.moveTo(0, -100);
ctx.lineTo(-8, -20);
ctx.lineTo(0, 0);
ctx.lineTo(8, -20);
ctx.lineTo(0, -100);
ctx.closePath();
ctx.fillStyle = '#000';
ctx.fill();
ctx.restore();
// 表盘分针
ctx.save();
ctx.translate(400, 300);
ctx.rotate(Math.PI/30 * min);
ctx.beginPath();
ctx.moveTo(0, -120);
ctx.lineTo(-8, -20);
ctx.lineTo(0, 0);
ctx.lineTo(8, -20);
ctx.lineTo(0, -120);
ctx.closePath();
ctx.fillStyle = 'blue';
ctx.fill();
ctx.restore();
// 表盘秒针
ctx.save();
ctx.translate(400, 300);
ctx.rotate(Math.PI/30 * sec);
ctx.beginPath();
ctx.moveTo(0, -150);
ctx.lineTo(-8, -20);
ctx.lineTo(0, 0);
ctx.lineTo(8, -20);
ctx.lineTo(0, -150);
ctx.closePath();
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.restore();
// 数字时间
ctx.save();
ctx.fillStyle = '#000';
ctx.font = 'bold 20px 微软雅黑';
ctx.translate(400, 300);
ctx.beginPath();
ctx.fillText(times, -38, 50, 200);
ctx.closePath();
ctx.fill();
ctx.restore();
}
clock();
setInterval(clock, 1000); // 每秒钟刷新一次
</script>
</body>
</html>