请使用firefox,chrome等最新浏览器浏览本站。

canvas 时钟

html5 阿豹 373次浏览 0个评论 扫描二维码

查看demo
canvas时钟代码:

var canvas = document.getElementById('clock');
var clock = canvas.getContext('2d');

function drowClock() {
	//清除画布
	clock.clearRect(0, 0, 300, 300);
	var now = new Date();
	var secd = now.getSeconds();
	var min = now.getMinutes();
	var hour = now.getHours();
	hour = hour + (min / 60);
	hour = hour > 12 ? hour - 12 : hour;
	//背景
	clock.beginPath();
	clock.lineWidth = 10;
	clock.strokeStyle = "blue";
	clock.arc(150, 150, 100, 0, 360, false);
	clock.stroke();
	clock.closePath();
	//刻度
	//时刻度
	for (var i = 0; i < 12; i++) {
		clock.save();
		//设置时针的粗细
		clock.lineWidth = 5;
		//设置时针的颜色
		clock.strokeStyle = "#000";
		//先设置0,0点
		clock.translate(150, 150);
		//再设置旋转角度
		clock.rotate((i * 30) * Math.PI / 180); //角度*Math.PI/180=弧度
		clock.beginPath();
		clock.moveTo(0, -94);
		clock.lineTo(0, -84);
		clock.closePath();
		clock.stroke();
		clock.restore();
	}
	//分刻度
	for (var i = 0; i < 60; i++) {
		clock.save();
		//设置时针的粗细
		clock.lineWidth = 2;
		//设置时针的颜色
		clock.strokeStyle = "#000";
		//先设置0,0点
		clock.translate(150, 150);
		//再设置旋转角度
		clock.rotate((i * 6) * Math.PI / 180); //角度*Math.PI/180=弧度
		clock.beginPath();
		clock.moveTo(0, -90);
		clock.lineTo(0, -84);
		clock.closePath();
		clock.stroke();
		clock.restore();
	}
	//时针
	clock.save();
	clock.lineWidth = 5;
	clock.strokeStyle = "black";
	clock.translate(150, 150);
	clock.rotate((hour+min/60) * 30 * Math.PI / 180);
	clock.beginPath();
	clock.moveTo(0, -75);
	clock.lineTo(0, 10);
	clock.stroke();
	clock.closePath();
	clock.restore();
	//分针
	clock.save();
	clock.lineWidth = 3;
	clock.strokeStyle = "black";
	clock.translate(150, 150);
	clock.rotate((min+secd/60) * 6 * Math.PI / 180);
	clock.beginPath();
	clock.moveTo(0, -80);
	clock.lineTo(0, 10);
	clock.stroke();
	clock.closePath();
	clock.restore();
	//秒针
	clock.save();
	clock.lineWidth = 3;
	clock.strokeStyle = "red";
	clock.translate(150, 150);
	clock.rotate(secd * 6 * Math.PI / 180);
	clock.beginPath();
	clock.moveTo(0, -80);
	clock.lineTo(0, 10);
	clock.closePath();
	clock.stroke();
	//画交叉点
	clock.beginPath();
	clock.lineWidth = 2;
	clock.arc(0, 0, 3, 0, 360, false);
	clock.closePath();
	clock.fillStyle = "gray";
	clock.fill();
	clock.stroke();
	clock.beginPath();
	clock.arc(0, -70, 3, 0, 360, false);
	clock.closePath();
	clock.fillStyle = "gray";
	clock.fill();
	clock.stroke();
	clock.restore();
}
drowClock();
setInterval(drowClock, 1000);

转载请注明canvas 时钟
喜欢 (1)or分享 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到