只是作为练习,没怎么抽象,都放在函数里面,只是简单的实现。
首先说下思路,将一个圆分成12份做表盘,然后用lineTo等方法话指针,最后用一个setInterval刷新画布,让指针每隔一秒动一下。
js代码如下:
window.onload = function () { var canvas = document.getElementById('myCanvas'), context = canvas.getContext('2d'), centerX = canvas.height / 2, centerY = canvas.width / 2, clockRadius = 100,//钟表的半径 radius = 5,//小圆的半径 secondHandLength =Math.ceil(clockRadius*0.9),//各种指针长度 minuteHandLength = Math.ceil(clockRadius*0.75), hourHandLength = Math.ceil(clockRadius*0.5); function drawClock() { //画表盘,每次刷新要重画所以提出来 drawCircle(centerX, centerY, radius, 'gray'); for (var i = 0; i < Math.PI * 2;) { var y = Math.sin(i) * clockRadius + centerY; var x = Math.cos(i) * clockRadius + centerX; drawCircle(x, y, radius); i += Math.PI / 6; } } function drawCircle(x, y, radius, color) { //画圆的基础方法 x = x || 0; y = y || 0; radius = radius || 5; color = color || 'lightseagreen'; context.save(); context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2); context.fillStyle = color; context.stroke(); context.fill(); context.closePath(); context.restore(); } function drawLine(startX, startY, endX, endY, lineWidth,color) { //画线的基础方法 startX = startX || 0; startY = startY || 0; endX = endX || 0; endY = endY || 0; lineWidth = lineWidth || 1; color = color||'black'; context.save(); context.beginPath(); context.strokeStyle=color; context.lineWidth = lineWidth; context.moveTo(startX, startY); context.lineTo(endX, endY); context.closePath(); context.stroke(); context.restore(); } function drawFrame() { //刷新画布的基础方法 context.clearRect(0, 0, canvas.width, canvas.height); //先清空画布,准备重新画 var d = new Date(), seconds = d.getSeconds(), //用second/60*Math.PI算出指针角度,由于钟表12点是0所以减个偏移量,让second=0 angle = seconds / 30 * Math.PI-Math.PI/2; //的时候指针指的是12点位置,里面能约的直接约了,省得多算几部 var endX = secondHandLength * Math.cos(angle); var endY = secondHandLength * Math.sin(angle); drawLine(centerX, centerY, endX+centerX, endY+centerY); //绘制秒针 //分针 var minutes = d.getMinutes(); angle = minutes/30*Math.PI-Math.PI/2; endX = Math.cos(angle)*minuteHandLength; endY = Math.sin(angle)*minuteHandLength; drawLine(centerX, centerY, endX+centerX, endY+centerY,1,'green'); //原理同上绘制分针 //时针 var hours = d.getHours(); angle = hours/6*Math.PI-Math.PI/2; endX = Math.cos(angle)*hourHandLength; endY = Math.sin(angle)*hourHandLength; drawLine(centerX, centerY, endX+centerX, endY+centerY,1,'blue'); //绘制时针 drawClock(); } drawFrame(); //setInterval一秒以后才启动,所以先画一次 setInterval(drawFrame, 1000); //将setInterval设置为1秒,每1秒刷新一次画布 }
下面是html中body的内容,就一个canvas
<canvas id="myCanvas" height="400" width="400" style="border-style:solid;"></canvas>
其实有些方法还是不太懂,但效果出来了,以后慢慢理解吧。。