今天上传一个前一阵子做的Canvas实例,时钟特效,是根据课程编写的,主要的是JS和Canvas
html代码:
@charset "utf-8";
body{
background-color: AntiqueWhite;
}
canvas{
background-color: white;
}
CSS代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>时钟</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/js.js"></script>
</head>
<body>
<canvas id="c1" width="400" height="400"></canvas>
</body>
</html>
重点来了~JS代码:
window.onload = function(){
var oC = document.getElementById('c1');
var oGC = oC.getContext('2d');
function toDraw(){
var x = 200;
var y = 200;
var r = 150;
oGC.clearRect(0,0,oC.width,oC.height);
var oDate = new Date();
var oHours = oDate.getHours();
var oMin = oDate.getMinutes();
var oSec = oDate.getSeconds();
var oHoursValue = (-90 + oHours*30 + oMin/2)*Math.PI/180;
var oMinValue = (-90 + oMin*6)*Math.PI/180;
var oSecValue = (-90 + oSec*6)*Math.PI/180;
// oGC.moveTo(x,y);
// oGC.arc(x,y,r,0,6*Math.PI/180,false);
// oGC.moveTo(x,y);
// oGC.arc(x,y,r,6*Math.PI/180,12*Math.PI/180,false);
// 小刻度
oGC.beginPath();
for( var i=0; i<60; i++ ){
oGC.moveTo(x,y);
oGC.arc(x,y,r,i*6*Math.PI/180,(i+1)*6*Math.PI/180,false);
}
oGC.closePath();
oGC.stroke();
oGC.fillStyle = 'white';
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*19/20,0,2*Math.PI,false);
oGC.closePath();
oGC.fill();
// 大刻度
oGC.lineWidth = 3;
oGC.beginPath();
for( var i=0; i<12; i++ ){
oGC.moveTo(x,y);
oGC.arc(x,y,r,i*30*Math.PI/180,(i+1)*30*Math.PI/180,false);
}
oGC.closePath();
oGC.stroke();
oGC.fillStyle = 'white';
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*18/20,0,2*Math.PI,false);
oGC.closePath();
oGC.fill();
// 时针
oGC.lineWidth = 5;
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*10/20,oHoursValue,oHoursValue,false);
oGC.closePath();
oGC.stroke();
// 分针
oGC.lineWidth = 3;
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*14/20,oMinValue,oMinValue,false);
oGC.closePath();
oGC.stroke();
// 秒针
oGC.lineWidth = 1;
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*19/20,oSecValue,oSecValue,false);
oGC.closePath();
oGC.stroke();
}
setInterval(toDraw,1000);
toDraw();
}
注意各文件之间路径写对哦~~