canvas实现时钟效果
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>时钟</title>
</head>
<body>
<canvas id="clock" width="500" height="500" style="background-color:black;">你的浏览器不支持canvas</canvas>
<script type="text/javascript">
var canvas = document.getElementById("clock");
var cxt = canvas.getContext("2d");
function drawClock() {
var now = new Date();
var sec = now.getSeconds();
var min = now.getMinutes();
var hour = now.getHours();
hour > 12 ? hour - 12 : hour;
hour += (min / 60);
//先清空画布
cxt.clearRect(0, 0, canvas.width, canvas.height);
//美女图片作为表盘背景
var img = new Image();
img.src = "tw.png";
cxt.drawImage(img, 46, 46);
//img.onload = function () {
// cxt.drawImage(img, 0, 0);
//}
//画表盘大圆 圆心:x=250 y=250
cxt.strokeStyle = "#00FFFF";
cxt.lineWidth = 10;
cxt.beginPath();
cxt.arc(250, 250, 200, 0, 360);
cxt.stroke();
cxt.closePath();
//时刻度
for (var i = 0; i < 12; i++) {
cxt.save();//保存当前状态
cxt.lineWidth = 7;
cxt.strokeStyle = "#FFFF00";
//设置原点
cxt.translate(250, 250);
//设置旋转角度
cxt.rotate(30 * i * Math.PI / 180);//弧度 角度*Math.PI/180
cxt.beginPath();
cxt.moveTo(0, -175);
cxt.lineTo(0, -195);
cxt.stroke();
cxt.closePath();
cxt.restore();//把原来状态恢复回来
}
//分刻度
for (var i = 0; i < 60; i++) {
cxt.save();
cxt.lineWidth = 5;
cxt.strokeStyle = "#FFFF00";
cxt.translate(250, 250);
cxt.rotate(i * 6 * Math.PI / 180);
cxt.beginPath();
cxt.moveTo(0, -185);
cxt.lineTo(0, -195);
cxt.stroke();
cxt.closePath();
cxt.restore();
}
//以下的时针、分针、秒针均要转动,所以在这里要设置其异次元空间的位置
//根据当前的小时数、分钟数、秒数分别设置各个针的角度即可
//-----------------------------时针-----------------------------
cxt.save();
cxt.lineWidth = 7;
cxt.strokeStyle = "#00FFFF";
cxt.translate(250, 250);
cxt.rotate(hour * 30 * Math.PI / 180);//每小时旋转30度
cxt.beginPath();
cxt.moveTo(0, -130);
cxt.lineTo(0, 10);
cxt.stroke();
cxt.closePath();
补充:web前端 , JavaScript ,