1. 程式人生 > >canvas 畫一個鐘表

canvas 畫一個鐘表

document move ets center logs con pre col 直接

只是作為練習,沒怎麽抽象,都放在函數裏面,只是簡單的實現。

首先說下思路,將一個圓分成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>

其實有些方法還是不太懂,但效果出來了,以後慢慢理解吧。。

canvas 畫一個鐘表