之前用 HTML+CSS+JavaScript 實現了一個簡單鐘表,但存在一些問題,主要是部分 CSS 屬性在不同瀏覽器的支援效果不一致,因此嘗試用 canvas 重新實現了一個簡單的鐘表。當然,採用 canvas 同樣會面臨某些瀏覽器不支援的情況,這裡只討論 canvas 的實現方式。
HTML 部分很簡單,寫入 canvas 標籤,其 id 設置為"canvas",用 CSS 設置成居中顯示:
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<style>
canvas{display:block;margin:5px auto;}
</style>
<title>clock</title>
</head>
<body>
<canvas id='canvas'>您的浏覽器不支持canvas標簽</canvas>
<script type='text/javascript' src="外部JavaScript文件路徑"></script>
</body>
</html>
備注:需要通過 script 標簽的 src 屬性引入外部 JavaScript 文件。
可以通過 js 獲取 Canvas 對象,設置畫布的寬高,繪圖工作則通過操作 CanvasRenderingContext2D 對象來進行:
var canvas = document.getElementById('canvas'); // Canvas對象
canvas.width = 450; // 寬
canvas.height = 450; // 高
var context = canvas.getContext('2d'); // 獲取繪圖上下文環境
獲取繪圖上下文 context 後即可繪制鐘表,整體思路是:定義一個全局變量記錄當前系統時間,用 setInterval 重復執行,獲取時間並繪制圖像:
var currentDateObj; // 記錄當前時間信息
setInterval(function(){
update(); // 修改currentDateObj的內容
draw(); // 根據currentDateObj的內容繪制圖像
}, 500);
本文實現重點在於繪制圖像,draw 方法主要涉及:線段和圓的繪制、canvas 文字渲染、canvas 陰影實現、canvas 圖形變換等。
繪制線段只需調用 moveTo、lineTo 設置路徑,再調用 stroke 完成繪制:
context.moveTo(20, 70); context.lineTo(140, 70); context.lineTo(140, 40); context.lineTo(180, 80); context.lineTo(140, 120); context.lineTo(140, 90); context.lineTo(20, 90); context.lineWidth = 2; context.strokeStyle = "#058"; context.stroke();
繪制圓需調用 arc 方法再 stroke,arc 有 5 個參數:圓心 x 坐標、y 坐標、半徑、起始角、結束角,最後一個布爾值 false 表示順時針、true 表示逆時針:
for(var i = 0; i < 2; i++) { for(var j = 0; j < 4; j++){ var b = (i == 0) ? false : true; context.beginPath(); context.lineWidth = 2; context.strokeStyle = '#058'; context.arc(150 * j + 75, 150 * i + 75, 45, 0, (j + 1) * Math.PI / 2, b); context.stroke(); } }
設置好路徑後調用 stroke 完成線稿,若需繪制實心區域則改用 fill 方法。
在 canvas 上寫文字分兩步:1. 通過 context 的 font 屬性設置文本樣式;2. 調用 fillText 或 strokeText 渲染文字:
context.font = "bold 40px Arial"; context.fillStyle = '#058'; context.fillText("Canvas制作簡單鐘表", 50, 50); context.strokeStyle = '#058'; context.strokeText("Canvas制作簡單鐘表", 50, 150);
還可設置 textAlign 和 textBaseline 分別控制文本水平和垂直方向的对齊方式。
設置陰影主要涉及:shadowColor 設置陰影顏色,shadowOffsetX/Y 設置 x、y 方向偏移量,shadowBlur 設置模糊程度:
context.shadowColor = "#444"; context.shadowOffsetX = 10; context.shadowOffsetY = 10; context.shadowBlur = 10; context.fillStyle = "#058"; context.fillRect(100, 50, 300, 100);
最基本的圖形變換方法:位移 translate(x, y)、旋轉 rotate(deg)、縮放 scale(sx, sy)。默認坐標原點 (0,0) 在 canvas 左上角,但對於鐘表來說,若能把原點移到表盤圓心,處理起來會很方便。需要注意的是 canvas 是基於狀態的,調用 translate 後原點會累加,所以實際調用時需用 save 保存當前狀態,繪制完畢後用 restore 還原。
clearRect 用於清空一個矩形空間的圖像,語法為 context.clearRect(x, y, width, height);。本例中 draw 方法的第一步就是調用它清空整個畫布,然後才根據 currentDateObj 的內容重新繪制。
(function(){
var config = {
canvas : { width : 420, height : 420 },
clock : {
radius : 200,
borderWidth : 10,
origin : { radius : 8, color : '#333' },
hand : {
hour : {width : 5, length : 80},
minute : {width : 2, length : 110},
second : {length : 160}
}
}
};
var canvas = document.getElementById('canvas');
canvas.width = config.canvas.width;
canvas.height = config.canvas.height;
var context = canvas.getContext('2d');
var currentDateObj;
setInterval(function(){ update(); draw(); }, 500);
function update(){
currentDateObj = getDateObj();
function getDateObj() {
var week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var date = d.getDate();
var day = d.getDay();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
month = (month < 9) ? '0' + month : '' + month;
date = (date < 9) ? '0' + date : '' + date;
hour = (hour < 9) ? '0' + hour : '' + hour;
minute = (minute < 9) ? '0' + minute : '' + minute;
second = (second < 9) ? '0' + second : '' + second;
var time = [hour, minute, second];
var str = year + '-' + month + '-' + date + ' ' + week[day];
return { dateStr: str, dateTime: time }
}
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawBorder(); drawScale(); drawNumbers(); drawTime(); drawHand(); drawOrigin();
function drawBorder() {
context.save(); context.beginPath();
context.arc(canvas.width / 2, canvas.height / 2, config.clock.radius, 0, 2 * Math.PI, false);
context.arc(canvas.width / 2, canvas.height / 2, config.clock.radius - config.clock.borderWidth, 0, 2 * Math.PI, true);
context.fillStyle = "#333"; context.shadowColor = "#444"; context.shadowBlur = 10;
context.closePath(); context.fill(); context.restore();
}
function drawOrigin() {
context.save(); context.beginPath();
context.arc(canvas.width / 2, canvas.height / 2, config.clock.origin.radius, 0, 2 * Math.PI, false);
context.fillStyle = config.clock.origin.color; context.shadowColor = "#444"; context.shadowBlur = 3;
context.closePath(); context.fill(); context.restore();
}
function drawScale() {
for(var i = 0; i < 60; i++) {
var obj = { sx : config.clock.radius - 15 - config.clock.borderWidth, sy : 0, ex : config.clock.radius - config.clock.borderWidth - 5, ey : 0, color : "#333", width : 1 };
context.save(); context.translate(canvas.width / 2, canvas.height / 2);
context.rotate(i * 6 * Math.PI / 180); context.beginPath();
if(i % 5 == 0) { obj.width = 3; obj.color = "#000"; }
if(i % 15 == 0) { obj.sx = config.clock.radius - 20 - config.clock.borderWidth; }
context.moveTo(obj.sx, obj.sy); context.lineTo(obj.ex, obj.ey);
context.strokeStyle = obj.color; context.lineWidth = obj.width;
context.closePath(); context.stroke(); context.restore();
}
}
function drawNumbers() {
var radius = config.clock.radius - config.clock.borderWidth - 40;
for(var i = 0; i < 12; i++) {
context.save(); context.beginPath(); context.translate(canvas.width / 2, canvas.height / 2);
context.font = "normal 28px Arial";
if((i + 1) % 3 == 0) { context.font = "normal 36px Arial"; }
context.textAlign = 'center'; context.textBaseline = 'middle';
context.fillText(i + 1, -radius * Math.cos((-i * 30 - 120) * Math.PI / 180), radius * Math.sin((-i * 30 - 120) * Math.PI / 180));
context.closePath(); context.restore();
}
}
function drawHand() {
var _hour = currentDateObj.dateTime[0] % 12;
var _minute = currentDateObj.dateTime[1];
var _second = currentDateObj.dateTime[2];
// 時針、分針、秒針分別透過 translate 到圓心、rotate 旋轉角度後繪制
}
}
}());
完整代碼已附上,透過 config 集中管理尺寸與樣式參數,再結合前面介紹的線段、圓、文字、陰影與變換技巧,即可繪製出一個具備指針、刻度、數字與日期顯示的完整 canvas 鐘表。