核心提示:canvas绘图API:arc()beginPath()clearRect()fill()fillText()lineTo()moveTo()stroke()canvas创建不可见的路径,然后用str...
canvas绘图API:
arc()
beginPath()
clearRect()
fill()
fillText()
lineTo()
moveTo()
stroke()
canvas创建不可见的路径,然后用stroke()来描绘路径的边缘,或者调用fill()来对路径的内部进行填充,是路径变得可见。可以调用beginPath()方法来开始定义某一段路径。
类似的还有drawCenter()方法,通过调用beginPath()、arc()、fill()来绘制时钟中心的那个实心圆。
drawNumerals()方法是通过调用fillText()来绘画钟面周围的数字,fillText()使用来在canvas中进行文本填充的。
drawHand()是钟表指针的绘制,用了三种绘画线段方法:moveTo()、lineTo()、stroke()。先调用moveTo()将画笔移动到canvas中的指定地点,然后调用lineTo()方法,在该点与另外一个指定的点之间绘制一条不可见的路径,最后用stroke()进行绘画出来。
应用程序通过调用setInterval()方法来制作时钟的动画效果,该方法每秒钟都会调用一次drawClock()函数,然后使用clearRect()方法进行擦除canvas,再重新绘制时钟。
绘制钟表:
drawCircle():绘制了一个表示钟面的圆形,方法先调用了beginPath()来开始定义路径,然后调用arc()来创建一个圆形的路径。
JavaScript代码:
var canvas = document.getElementById('canvas'); context = canvas.getContext('2d'); FONT_HEIGHT = 15; MARGIN = 35; HAND_TRUNCATION = canvas.width/25; HOUR_HAND_TRUNCATION = canvas.width/10; NUMERAL_SPACING = 20; RADIUS = canvas.width/2 - MARGIN; HAND_RADIUS = RADIUS + NUMERAL_SPACING; //画外圆 function drawCircle(){ context.beginPath(); context.arc(canvas.width/2,canvas.height/2,RADIUS,0,Math.PI*2,true); context.stroke(); } function drawNumerals(){ var numerals = [1,2,3,4,5,6,7,8,9,10,11,12]; angle = 0; numeralWidth = 0; numerals.forEach(function(numeral){ angle = Math.PI/6*(numeral-3); numeralWidth = context.measureText(numeral).width; context.fillText(numeral,canvas.width/2+Math.cos(angle)*(HAND_RADIUS)-numeralWidth/2,canvas.height/2+Math.sin(angle)*(HAND_RADIUS)+FONT_HEIGHT/3); }); } function drawCenter(){ context.beginPath(); context.arc(canvas.width/2,canvas.height/2,5,0,Math.PI*2,true); context.fill(); } function drawHand(loc,isHour){ var angle = (Math.PI*2)*(loc/60)-Math.PI/2; handRadius = isHour?RADIUS - HAND_TRUNCATION - HOUR_HAND_TRUNCATION : RADIUS - HAND_TRUNCATION; context.moveTo(canvas.width/2,canvas.height/2); context.lineTo(canvas.width/2+Math.cos(angle)*handRadius,canvas.height/2+Math.sin(angle)*handRadius); context.stroke(); } function drawHands(){ var date = new Date, hour = date.getHours(); hour = hour > 12 ? hour - 12 : hour; drawHand(hour*5+(date.getMinutes()/60)*5,true,0.5); drawHand(date.getMinutes(),false,0.5); drawHand(date.getSeconds(),false,0.2); } function drawClock(){ context.clearRect(0,0,canvas.width,canvas.height); drawCircle(); drawCenter(); drawHands(); drawNumerals(); } context.font = FONT_HEIGHT + 'px Arial'; loop = setInterval(drawClock,1000);
html的代码就只要画一个桌布canvas就好了