canvas绘制时钟

Posted zhanghaifeng123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了canvas绘制时钟相关的知识,希望对你有一定的参考价值。

技术图片

var canvas = document.getElementById("canvas");

var ctx = canvas.getContext(‘2d‘);
var rem = 500 / 200;

function clock() {
ctx.clearRect(0, 0, 500, 500)
var now = new Date();
var second = now.getSeconds();
var minute = now.getMinutes();
var hour1 = now.getHours();
var hour = hour1 + minute / 60;
hour = hour > 12 ? hour - 12 : hour;

var year = now.toLocaleDateString()
var time = now.toLocaleTimeString()
ctx.font = "18px Arial"
ctx.fillText(year + time, 160, 200)


//表盘
ctx.beginPath()
ctx.lineWidth = ‘8‘
var gradient = ctx.createLinearGradient(0, 0, 500, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "yellow");
gradient.addColorStop(1, "blue");
ctx.arc(250, 250, 200, 0, Math.PI * 2)
ctx.strokeStyle = gradient
ctx.stroke()
ctx.closePath()

// fun()
//时针

for (var i = 0; i < 12; i++) {
ctx.save()
ctx.strokeStyle = "black"
ctx.translate(250, 250)
ctx.rotate(30 * Math.PI / 180 * i)
ctx.beginPath()
ctx.lineWidth = 4
ctx.moveTo(0, -196)
ctx.lineTo(0, -180)

// ctx.font = ‘25px Arial bold‘;
// if (i == 0) {
// ctx.fillText(12, -12, -150)
// } else {
// ctx.fillText(i, -12, -150)
// }


ctx.stroke()
ctx.closePath()
ctx.restore()
// ctx.translate(250, 250)

}

 

//60 刻度
for (var i = 0; i < 60; i++) {
ctx.save()

ctx.strokeStyle = "black"
ctx.translate(250, 250)
ctx.rotate(6 * Math.PI / 180 * i)
ctx.beginPath()
ctx.lineWidth = 2

ctx.moveTo(0, -196)
ctx.lineTo(0, -188)
ctx.stroke()
ctx.closePath()
ctx.restore()
}

 


ctx.save();
ctx.lineWidth = 3;
ctx.strokeStyle = "black";
ctx.translate(250, 250);
ctx.rotate(Math.PI / 180 * 30 * hour)
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -80);
ctx.closePath();
ctx.stroke();
ctx.restore()

ctx.save();
ctx.lineWidth = 2;
ctx.strokeStyle = "red"
ctx.translate(250, 250);
ctx.rotate(Math.PI / 180 * 6 * minute)
ctx.beginPath();
ctx.moveTo(-2, 0);
ctx.lineTo(0, -130);
ctx.closePath();
ctx.stroke();
ctx.restore()
ctx.save();

ctx.lineWidth = 1;
ctx.strokeStyle = "pink";
ctx.translate(250, 250);
ctx.rotate(Math.PI / 180 * 6 * second)
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -150);
ctx.closePath();
ctx.stroke();
ctx.restore()

 


ctx.beginPath()
ctx.strokeStyle = ‘skyblue‘;
ctx.arc(251, 250, 1, 0, Math.PI * 2)
ctx.closePath()
ctx.stroke()

ctx.save()
ctx.translate(250, 250)
fun()
ctx.restore()
}
clock()

//数字刻度

function fun() {
var arr = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2]
ctx.font = "40px Arial";
ctx.textAlign = ‘center‘;
ctx.textBaseline = ‘middle‘;
for (var j = 0; j < arr.length; j++) {
var rad = Math.PI * 2 / 12 * j;
var x = Math.cos(rad) * (160);
var y = Math.sin(rad) * (160);
ctx.fillText(arr[j], x, y);
}
}

setInterval(clock, 1000)

以上是关于canvas绘制时钟的主要内容,如果未能解决你的问题,请参考以下文章

Canvas绘制时钟

Canvas - 时钟绘制

H5之canvas-绘制动态时钟

canvas绘制一个数字时钟

用canvas绘制一个简易时钟

canvas绘制时钟