您的位置:首页 > Web前端 > JavaScript

canvas标签结合javascript做出动态时钟效果

2015-04-10 16:34 597 查看
代码如下:

<!doctype html>

<head>

<meta charset="utf-8">

<style type="text/css">

body{

background: purple;

}

</style>

</head>

<body>

<canvas id="liuzhe" width="500" height="500"></canvas>

<script type="text/javascript">

var clock=document.getElementById("liuzhe");

var cxt=clock.getContext("2d");

function drawclock(){

//清除画布

cxt.clearRect(0,0,500,500)

var now=new Date();

var sec=now.getSeconds();

var min=now.getMinutes();

var hour=now.getHours();

hour=hour>12?hour-12:hour;

//画圆

cxt.lineWidth=10;

cxt.strokeStyle="red";

cxt.beginPath();

cxt.arc(250, 250, 200, 0, 360, false);

cxt.closePath();

cxt.stroke();

//小时

for(var i=0;i<12;i++){

cxt.save();

cxt.lineWidth=7;

cxt.strokeStyle="#000";

cxt.translate(250, 250);

cxt.rotate(i*30*Math.PI/180);

cxt.beginPath();

cxt.moveTo(0, -170);

cxt.lineTo(0, -190);

cxt.closePath();

cxt.stroke();

cxt.restore();

}

//分钟

for(var i=0;i<60;i++){

cxt.save();

cxt.lineWidth=5;

cxt.strokeStyle="#000"

cxt.translate(250, 250);

cxt.rotate(sec*6*Math.PI/180);

cxt.beginPath();

cxt.moveTo(0, -180);

cxt.lineTo(0, -190);

cxt.closePath();

cxt.stroke();

cxt.restore();

}

//时针

cxt.save();

cxt.lineWidth=7;

cxt.strokeStyle="#000";

cxt.translate(250, 250);

cxt.rotate(hour*30*Math.PI/180);

cxt.beginPath();

cxt.moveTo(0, -140);

cxt.lineTo(0, 10);

cxt.closePath();

cxt.stroke();

cxt.restore();

//分针

cxt.save();

cxt.lineWidth=5;

cxt.strokeStyle="#000";

cxt.translate(250, 250);

cxt.rotate(min*6*Math.PI/180);

cxt.beginPath();

cxt.moveTo(0, -160);

cxt.lineTo(0, 15);

cxt.closePath();

cxt.stroke();

cxt.restore();

//秒针

cxt.save();

cxt.lineWidth=3;

cxt.strokeStyle="red";

cxt.translate(250, 250);

cxt.rotate(sec*6*Math.PI/180);

cxt.beginPath();

cxt.moveTo(0, -170);

cxt.lineTo(0, 20);

cxt.closePath();

cxt.stroke();

cxt.restore();

}

//周期循环时间

setInterval(drawclock, 1000);

</script>

</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: