<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas width="500" height="500" style="border: 1px solid #eeeeee"></canvas>
<script>
var ctx = document.querySelector('canvas').getContext('2d');
//图片
var img = new Image();
// img.onload = function () {
// ctx.drawImage(img, 0, 0, 500, 500, 0, 0, 1000, 1000);
// }
img.src = 'image/1.jpg';
function clock() {
ctx.clearRect(0, 0, 500, 500)
//获取当前的时分秒
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
h = h > 13 ? (h - 12) : h;
function time(e) {
return e = e < 10 ? '0' + e : e;
}
//画圆
ctx.beginPath();
ctx.arc(250, 250, 200, 0, 2 * Math.PI);
ctx.strokeStyle = "yellow";
ctx.lineWidth = 5;
ctx.fillStyle = 'rgb(60,253,126)'
ctx.fill();
// ctx.drawImage(img, 0, 0, 250, 250, 10, 10, 470, 470);
ctx.stroke();
ctx.clip()//裁剪
//时间
var textTime = time(h) + ':' + time(m) + ':' + time(s)
ctx.beginPath();
ctx.font = "20px 宋体"
ctx.fillText(textTime, 210, 400);
ctx.fillStyle = 'rgb(60,253,126)'
ctx.fill()
h = h + m / 60;
//时刻度
for (var i = 0; i < 12; i++) {
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(i * 30 * Math.PI / 180);
ctx.moveTo(0, -185);
ctx.lineTo(0, -200);
ctx.strokeWidth = 8;
ctx.strokeStyle = 'yellow'
ctx.stroke();
ctx.restore();//恢复当前的状态
}
//分刻度
for (var i = 0; i < 60; i++) {
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(i * 6 * Math.PI / 180);
ctx.moveTo(0, -190);
ctx.lineTo(0, -200);
ctx.strokeWidth = 8;
ctx.strokeStyle = 'yellow'
ctx.stroke();
ctx.restore();//恢复当前的状态
}
//时针
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(h * 30 * Math.PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -100);
ctx.lineWidth = 7;
ctx.strokeStyle = 'pink'
ctx.stroke();
ctx.restore();//恢复当前的状态
//分针
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(m * 6 * Math.PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -120);
ctx.lineWidth = 5;
ctx.strokeStyle = 'pink'
ctx.stroke();
ctx.restore();//恢复当前的状态
//秒针
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(s * 6 * Math.PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -160);
ctx.lineWidth = 3;
ctx.strokeStyle = 'pink'
ctx.stroke();
ctx.restore();//恢复当前的状态
//秒针上的圆
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(s * 6 * Math.PI / 180);
ctx.arc(0, -130, 4, 0, 2 * Math.PI)
ctx.fillStyle = 'yellow'
ctx.fill()
ctx.strokeStyle = "pink"
ctx.lineWidth = 2;
ctx.stroke()
ctx.restore();//恢复当前的状态
//圆心
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.arc(0, 0, 6, 0, 2 * Math.PI)
ctx.fillStyle = 'yellow'
ctx.fill()
ctx.strokeStyle = "pink"
ctx.lineWidth = 2;
ctx.stroke()
ctx.restore();//恢复当前的状态
}
setInterval(clock, 1000)
clock();
</script>
</body>
</html>
在canvas中画钟
猜你喜欢
转载自blog.csdn.net/qq_44388393/article/details/88403954
今日推荐
周排行