您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)如何在JavaScript中使用Canvas繪制一個(gè)圓形時(shí)鐘效果,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
具體內(nèi)容如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Canvas Clock</title> <style type="text/css"> div{ text-align: center; margin-top: 250px; } #clock{ border: 1px solid #ccc; } </style> </head> <body> <div> <canvas id="clock" height="200px" width="200px"></canvas> </div> <script type="text/javascript" src="js/clock.js"></script> </body> </html>
js
var dom=document.getElementById('clock'); var cxt=dom.getContext("2d"); var width=cxt.canvas.width; var height=cxt.canvas.height; var r=width/2; function drawBackground(){ cxt.save(); cxt.translate(r,r); cxt.beginPath(); cxt.lineWidth=10; cxt.arc(0,0,r-5,0,2*Math.PI,false); cxt.stroke(); cxt.font="18px Arial"; cxt.textAlign='center' cxt.textBaseline='middle' var hourNums=[3,4,5,6,7,8,9,10,11,12,1,2]; hourNums.forEach(function(number,i){ var rad=2*Math.PI/12*i; var x=Math.cos(rad)*(r-30); var y=Math.sin(rad)*(r-30); cxt.fillText(number,x,y); }); for(var i=0;i<60;i++){ var rad=2*Math.PI/60*i; var x=Math.cos(rad)*(r-18); var y=Math.sin(rad)*(r-18); cxt.beginPath(); if(i % 5===0){ cxt.fillStyle="#000" cxt.arc(x,y,2,0,2*Math.PI,false); } else{ cxt.fillStyle="#ccc" cxt.arc(x,y,2,0,2*Math.PI,false); } cxt.fill(); } } function drawHour(hour,minute){ cxt.save(); cxt.beginPath(); var rad=2*Math.PI/12*hour; var mrad=2*Math.PI/12/60*minute cxt.rotate(rad+mrad); cxt.lineWidth=6; cxt.lineCap='round' cxt.moveTo(0,10); cxt.lineTo(0,-r/2); cxt.stroke(); cxt.restore(); } function drawMinute(minute){ cxt.save(); cxt.beginPath(); var rad=2*Math.PI/60*minute; cxt.rotate(rad); cxt.lineWidth=3; cxt.lineCap='round' cxt.moveTo(0,10); cxt.lineTo(0,-r+30); cxt.stroke(); cxt.restore(); } function drawSecond(second){ cxt.save(); cxt.beginPath(); cxt.fillStyle='#c14543' var rad=2*Math.PI/60*second; cxt.rotate(rad); cxt.moveTo(-2,20); cxt.lineTo(2,20); cxt.lineTo(1,-r+18); cxt.lineTo(-1,-r+18); cxt.fill(); cxt.restore(); } function drawDot(){ cxt.beginPath(); cxt.fillStyle='#fff' cxt.arc(0,0,3,0,2*Math.PI,false); cxt.fill(); } function draw(){ cxt.clearRect(0,0,width,height); var now=new Date(); var hour=now.getHours(); var minute=now.getMinutes(); var second=now.getSeconds(); drawBackground(); drawHour(hour,minute); drawMinute(minute); drawSecond(second); drawDot(); cxt.restore(); } draw(); setInterval(draw,1000);
上述就是小編為大家分享的如何在JavaScript中使用Canvas繪制一個(gè)圓形時(shí)鐘效果了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。