這篇文章主要介紹了JavaScript中canvas動畫實現時鐘效果的方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>時鐘特效</title>
</head>
<body>
<canvas width="150" height="150" id="canvas"></canvas>
</body>
</html>
<script>
clock();// 顯示
setInterval(clock,1000);// 每一秒重繪一次,達到轉動效果
function clock(){
var now = new Date();// 得到當前日期與時間
var second = now.getSeconds(),
min = now.getMinutes(),
hour = now.getHours();// 得到時分秒
hour = hour > 12?hour-12:hour;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0,0,150,150);// 初始化畫布
ctx.save();
ctx.translate(75,75);// 平移坐標原點
ctx.scale(0.4,0.4);//縮放效果
ctx.rotate(-Math.PI/2);// 將x軸旋轉-90
ctx.strokeStyle = 'black';
ctx.fillStyle = 'black';
ctx.lineWidth = 8;
ctx.lineCap = 'round';
// 顯示時針刻度
ctx.save();
ctx.beginPath();
for(var i = 0;i<12;i++)
{
ctx.rotate(Math.PI/6);
ctx.moveTo(100,0);
ctx.lineTo(120,0);
}
ctx.stroke();
ctx.closePath();
ctx.restore();// 恢復
ctx.save();
// 顯示秒針刻度
ctx.beginPath();
ctx.lineWidth = 5;
for(var i = 0;i < 60; i++)
{
if(i % 5 != 0)
{
ctx.moveTo(117,0);
ctx.lineTo(120,0);
}
ctx.rotate(Math.PI/30);// 轉6度
}
ctx.stroke();
ctx.closePath();
ctx.restore();// 恢復
ctx.save();
// 繪制時針
ctx.beginPath();
ctx.rotate((Math.PI / 6)*hour + (Math.PI/360)*min + (Math.PI /21600)*second)//時針當前指向的位置
ctx.lineWidth = 14;
ctx.moveTo(-20,0);
ctx.lineTo(75,0);
ctx.stroke();
ctx.closePath();
ctx.restore();//恢復
ctx.save();
// 繪制分針
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 10;
ctx.rotate((Math.PI/30)*min + (Math.PI/1800)*second);// 分針當前的位置
ctx.moveTo(-28,0);
ctx.lineTo(102,0);
ctx.stroke();
ctx.closePath();
ctx.restore();//恢復
ctx.save();
// 繪制秒針
ctx.beginPath();
ctx.rotate(Math.PI/30*second);
ctx.strokeStyle = '#D40000';
ctx.lineWidth = 6;
ctx.moveTo(-30,0);
ctx.lineTo(83,0);
ctx.stroke();
ctx.closePath();
ctx.restore();//恢復
ctx.save();
//繪制表框
ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle = '#325Fa2';
ctx.arc(0,0,142,0,Math.PI*2,true);//半徑142
ctx.stroke();
ctx.closePath();
ctx.restore()//恢復
ctx.restore()//恢復
}
</script>1、能夠嵌入動態文本于HTML頁面。2、對瀏覽器事件做出響應。3、讀寫HTML元素。4、在數據被提交到服務器之前驗證數據。5、檢測訪客的瀏覽器信息。6、控制cookies,包括創建和修改等。7、基于Node.js技術進行服務器端編程。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“JavaScript中canvas動畫實現時鐘效果的方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。