canvas绘制时针,适合初学者——李帅醒博客

版权声明:本文为博主 我吃酸萝卜/李帅醒 原创, 未经博主允许不得转载。新浪微博@我吃酸萝卜 https://blog.csdn.net/wcslb/article/details/53889819

篇文章主要介绍了使用canvas绘制超炫时钟的方法及代码,这里推荐给大家,步骤详细。

先上效果图

为了方便初学者学习,我特意在canvas画布上画好了小方格,方便计算坐标。

HTML页面代码:

<body>
    <canvas width="500px" height="500px">
        您的浏览器不支持canvas画布,请及时更新!!!
    </canvas>
    <table> </table>
</body>
CSS代码:

<style type="text/css">
*{
    margin:0px;
    padding: 0px;
}
    table {
        border-collapse: collapse;
        position: absolute;
        top: 50px;
        left: 50px;
    }

    table td {
        width: 49px;
        height: 49px;
        border: 1px dotted #ccc;
    }
    canvas{
        margin:50px;
        box-shadow: 2px 2px 5px;
        background: greenyellow;
    }

</style>
JS代码:
<script type="text/javascript">
    var table = document.querySelector("table");
for (var i = 0; i < 10; i++) {
    var tr = document.createElement("tr");
    for (var j = 0; j < 10; j++) {
        var td = document.createElement("td");
        tr.appendChild(td);
    }
    table.appendChild(tr);
}
var canvas=document.querySelector("canvas");
var ctx=canvas.getContext("2d");
// 秒针角度
var deg=Math.PI*2/60;
//画表盘
function watch(){
	ctx.beginPath();
	ctx.arc(250,250,250,0,Math.PI*2);
	ctx.lineWidth=10;
	ctx.stroke();
	ctx.beginPath();
	// 画分针刻度
	for(var i=0;i<60;i++){
		ctx.save();
		ctx.lineWidth=1;
	//把基点设置为圆心
		ctx.translate(canvas.width/2,canvas.height/2);
		ctx.rotate(deg*i);
		ctx.moveTo(canvas.width/2 ,0);
        ctx.lineTo(canvas.width/2-20,0);
        ctx.stroke();
        ctx.restore();      
	}
	//画时针刻度
	ctx.beginPath();
		for(var i=0;i<12;i++){
		ctx.save();
		ctx.lineWidth=4;
		ctx.translate(canvas.width/2,canvas.height/2);
		ctx.rotate(Math.PI*2/12*i);
		ctx.moveTo(canvas.width/2 ,0);
        ctx.lineTo(canvas.width/2-30,0);
        ctx.stroke();
        ctx.restore();      
	}
}
function Pointer(deg,Lwidth,color,mwidth){
	ctx.beginPath();
	ctx.save();
	ctx.translate(canvas.width/2,canvas.height/2);
	ctx.rotate(deg);					//旋转角度
	ctx.strokeStyle=color;				//颜色
	ctx.lineWidth=Lwidth;				//指针宽度	
	ctx.moveTo(0,-mwidth);   			//指针半径
	ctx.lineTo(0,0);
	ctx.stroke();
    ctx.restore();
}
var i=0;
//获取时间,给指针一个初始角度
var nowDate=new Date();
var houer=(12+nowDate.getHours())%12*(Math.PI*2/12);
var minutes=nowDate.getMinutes()*(deg);
var Seconds=nowDate.getSeconds()*(deg);
setInterval(function(){
	i++;
	ctx.clearRect(0,0,500,500);
	watch();
	//秒针运动
	Pointer(deg*i+Seconds,1,"red",canvas.width/2-40);
	//分针运动
	Pointer(deg/60*i+minutes,4,"purple",canvas.width/2-70);
	//时针运动
	Pointer(deg/60/60/12*i+houer,6,"#000",canvas.width/2-70);
},1000)
</script>
(我吃酸萝卜 新浪微博http://www.weibo.com/wcslb          ---李帅醒著)

猜你喜欢

转载自blog.csdn.net/wcslb/article/details/53889819