HTML5簡稱H5,現在因為很火,很多人都在學。canvas是屬於H5裡面的一個標籤,它有很強大的繪畫功能。當然,這些功能不是說用HTML標籤就能實現,它還要結合JavaScript一起完成。
這次是用canvas繪畫簡單的時鐘,整體思路:先畫框drawBackground,然後把時針(drawHour),分針(drawMinute),秒針(drawSecond)分別畫出來. 畫完之後就開始實現動畫了。動畫實現是先清除整個繪畫,然後再重新畫一遍鍾,每秒執行一次。
//canvas的div結構 內容很少
<canvas>
//先畫框
function drawBackground(){
ctx.save();//保存當前環境狀態
ctx.translate(r,r);//重新定義原點座標,正方形的正中心
ctx.beginPath();//起始路徑
ctx.lineWidth = 10 * em;//加粗10像素
ctx.arc(0,0,r-5*em,0,2*Math.PI,false);//創建圓
ctx.stroke();//設置繪畫方式,畫線
var hours = [3,4,5,6,7,8,9,10,11,12,1,2];//定義時間數組
ctx.font = 16 * em + "px Arial"//字體和字體大小
ctx.textAlign = 'center';//數字相對圓心左右兩邊居中
ctx.textBaseline = 'middle';//數字相對圓心上線兩邊居中
//畫時刻
hours.forEach(function(number , i){
var rad = 2 * Math.PI / 12 * i; //把圓分12個弧度
var x = Math.cos(rad) * (r - 30 * em);
var y = Math.sin(rad) * (r - 30 * em);
ctx.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 * em);
var y = Math.sin(rad) * (r - 18 * em);
ctx.beginPath();
//如果是整時就實黑點 不是就虛點
if(i % 5 === 0){
ctx.fillStyle = '#000';
ctx.arc(x, y, 2 * em, 0, 2 * Math.PI, false);
}else{
ctx.fillStyle = '#ccc';
ctx.arc(x, y, 2 * em, 0, 2 * Math.PI, false);
}
ctx.fill();//填充
}
}
//畫時針
function drawHour(hour, minute){
ctx.save();
var rad = 2 * Math.PI / 12 * hour;
var mrad = 2 * Math.PI / 12 / 60 * minute;
ctx.beginPath();
ctx.rotate(rad + mrad);//旋轉角度
ctx.lineWidth = 6 * em;//時針寬度
ctx.lineCap = 'round';//線條的每個末端添加圓形線帽
ctx.moveTo(0, 10 * em);
ctx.lineTo(0, -r / 2);
ctx.stroke();
ctx.restore();
}
//畫分針
function drawMinute(minute){
ctx.save();
var rad = 2 * Math.PI / 60 * minute;
ctx.beginPath();
ctx.rotate(rad);//旋轉角度
ctx.lineCap = 'round';//線條的每個末端添加圓形線帽
ctx.lineWidth = 4 * em;
ctx.moveTo(0, 10 * em);
ctx.lineTo(0, -r + 30 * em);
ctx.stroke();
ctx.restore();
}
//畫秒針
function drawSecond(second){
ctx.save();
ctx.beginPath();
ctx.fillStyle = '#c14543';
var rad = 2 * Math.PI / 60 * second;
ctx.rotate(rad);
ctx.moveTo(-2 * em, 20 * em);
ctx.lineTo(2 * em, 20 * em);
ctx.lineTo(1, -r + 18 * em);
ctx.lineTo(-1, -r + 18 * em);
ctx.fill();
ctx.restore();
}
//畫中心點
function drawDot(){
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.arc(0, 0, 3 * em, 2*Math.PI, false);
ctx.fill();
}
//獲取時間繪製走向
function draw(){
ctx.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();
ctx.restore();//返回之前保存的路徑狀態和屬性
}
draw(); //先執行一次繪畫
setInterval(draw, 1000);//實現動畫
頭條寫代碼很不爽,看代碼更不爽。不過這也沒辦法,大家將就吧。
閱讀更多 學霸IT 的文章
關鍵字: 標籤 HTML5 JavaScript